Share my C++ solution, very easy to understand


  • 0
    V
    class Solution {
    public:
        bool canConstruct(string ransomNote, string magazine) {
            int note_len = ransomNote.length();
            int magazine_len = magazine.length();
            int notes[26];
            int magas[26];
            
            if (note_len > magazine_len)
                return false;
            
            memset(notes, 0, sizeof(int) * 26);
            memset(magas, 0, sizeof(int) * 26);
            
            for (int i = 0; i < note_len; i++)
                notes[ransomNote[i] - 'a']++;
            for (int i = 0; i < magazine_len; i++)
                magas[magazine[i] - 'a']++;
            
            for (int i = 0; i < 26; i++)
            {
                if (notes[i] > magas[i])
                    return false;
            }
            
            return true;
        }
    };
    

Log in to reply
 

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