Simple way using O(n) time and O(1) space


  • -1
    X
    class Solution {
    public:
        bool isAnagram(string s, string t) {
            vector<int> m1(128,0),m2(128,0);
            int ns = s.length(),nt = t.length();
            if(ns != nt) return false;
            for(int i =0;i<ns;i++)
            {
                m1[s[i]]++;
                m2[t[i]]++;
            }
            for(int i = 0;i<128;i++)
            {
                if(m1[i]!=m2[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.