Short C++ solution, O(N) time, O(1) space


  • 0
    X
    bool isAnagram(string s, string t) {
        if(s.size() != t.size()) return false;
    
        vector<unsigned int> r;
        r.resize(256, 0);
        
        for(auto& c : s) ++r[c];
        for(auto& c : t) --r[c];
        
        return find_if(r.begin(), r.end(), [](unsigned int e){return e != 0;}) == r.end();
    }

  • 0
    F

    The last line 'find_if' step is needless. Here is my code!

    class Solution {
    public:
        bool isAnagram(string s, string t) {
            if(s.size() != t.size())
                return false;
            int count[26] = {0};
            for(auto &v : s)
                ++count[v - 'a'];
            for(auto &v : t)
                if(!count[v - 'a']--)
                    return false;
            return true;
        }
    };

  • 1
    S

    on iteration over t, the check if the count has been cancelled out should be done only after it goes through the whole t string.


Log in to reply
 

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