12 ms solution with array[26]


  • -1

    Use arr[26] instead of hash table to record count of each alphabet.

    bool isAnagram(string s, string t) 
    {
    	if (!s.size() && !t.size())
    		return 1;
    	if (!s.size() || !t.size() || s.size() != t.size())
    		return 0;
    	int sz = s.size();
    	int arr[26] = { 0 };
    	int i;
    	for (i = 0; i < sz; ++i)
    		arr[s[i] - 'a'] += 1;
    	for (i = 0; i < sz; ++i)
    	{
    		arr[t[i] - 'a'] -= 1;
    		if (arr[t[i] - 'a'] < 0)
    			return 0;
    	}
    	for (i = 0; i < 26; ++i)
    {
    	if (arr[i]) return 0;
    }
    return 1;
    

    }


  • 0
    X

    why so complicated.

    bool isAnagram(string s, string t) {
        vector<int> tbl(26, 0);
        for (auto c : s)
            tbl[c - 'a'] ++;
        for (auto c : t)
            tbl[c - 'a']--;
        for (auto i : tbl)
            if (i != 0)
                return false;
        return true;
    }

  • 0

    Yes, you're right, my code is not quite neat, thank you for your solution. But as I'm not a sophisticated coder and my priority is to solve the problem. Neat and concise code is my next phase.


  • 0
    H

    Simple C Style

      bool isAnagram(char* s, char* t) {
         int have[256]={0};
         while(*s) have[*(s++)]++;
         while(*t) have[*(t++)]--;
         for(char tmp = 'a';tmp <= 'z'; ++tmp)
             if(have[tmp])
                return false;
        return true;
    }

Log in to reply
 

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