19ms Easy to Understand C++ solution


  • 2
    D
    class Solution {
    public:
        bool canConstruct(string ransomNote, string magazine) {
            int lettersLeft = ransomNote.size(); // Remaining # of letters to be found in magazine
            int arr[26] = {0};
            for (int j = 0; j < ransomNote.size(); j++) {
                arr[ransomNote[j] - 'a']++; // letter - 'a' gives a value of 0 - 25 for each lower case letter a-z
            }
            
            int i = 0;
            while (i < magazine.size() && lettersLeft > 0) {
                if (arr[magazine[i] - 'a'] > 0) {
                    arr[magazine[i] - 'a']--;
                    lettersLeft--;
                }
                i++;
            }
            if (lettersLeft == 0) {
                return true;
            } else {
                return false;
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.