Simplest solution in C++


  • -1
    A
    public:
        bool canConstruct(string ransomNote, string magazine) {
            map <char,int> m;
            map <char,int> r;
            int l =ransomNote.size();
            int n = magazine.size();
            
            if(l>n){                    // to optimize little bit
                return false;
            }
            
            for(int i=0;i<n;i++){
                m[magazine[i]]++;
            }
            
            for(int i=0;i<l;i++){
                if(m[ransomNote[i]] > 0 ){
                    m[ransomNote[i]]--;
                }
                else return false;
            }
            return true;
        }
    }; ```

Log in to reply
 

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