C++ Simple Solution, easy to understand.


  • 0
    E

    first loop is to count numbers of each element in the magazine, second loop is to decrease the number by 1 when it is used.

    So when the number is decrease to 0 (run out) and if the program still try to match a character "c" in the magazine, it will return false, otherwise it will return true at the end.

    Thanks, please reply if you want me to clarify anything or you got a better idea to help me to optimize it, thank you!

    class Solution {
    public:
        bool canConstruct(string ransomNote, string magazine) {
            unordered_map <char, int> m;
            for (auto c:magazine){
                m[c]++;
            }
            for (auto c: ransomNote){
                if (m[c] == 0) return false;
                m[c]--;
            }
            return true;
        }
    };
    

Log in to reply
 

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