28ms C++ solution


  • 1
    class Solution {
    public:
    bool canConstruct(string ransomNote, string magazine) {
        int m[26]; memset(m, 0, sizeof(m));
        int cnt = 0;
        
        for (char c : ransomNote) {
            m[c - 'a']++, cnt++;
        }
        
        for (char c : magazine) {
            if (m[c - 'a'] > 0) {
                m[c - 'a']--;
                if (--cnt == 0) {
                    return true;
                }
            } 
        }
        
        return cnt == 0;
    }
    };

  • 1

    Added three more lines and made it 24ms:

    class Solution {
    public:
    bool canConstruct(string ransomNote, string magazine) {
        if (ransomNote.length() > magazine.length()) {
            return false;
        }
        int m[26]; memset(m, 0, sizeof(m));
        int cnt = 0;
        
        for (char c : ransomNote) {
            m[c - 'a']++, cnt++;
        }
        
        for (char c : magazine) {
            if (m[c - 'a'] > 0) {
                m[c - 'a']--;
                if (--cnt == 0) {
                    return true;
                }
            } 
        }
        
        return cnt == 0;
    }
    };

Log in to reply
 

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