6 line solution, c++ easy to understand, using constant space


  • 0
    H
    class Solution {
        public:
            bool isAnagram(string s, string t) {
                vector<int> v(26,0);
                int l1=s.size(),l2=t.size();
                for(int i=0;i<l1;i++)        v[s[i]-'a']++;
                for(int i=0;i<l2;i++)        v[t[i]-'a']--;
                for(int i=0;i<26;i++)  if(v[i]!=0) return false;
                return true;
            }
        };

  • -2
    E
    bool IsAnagram(string str1, string str2)
    {
    	if(str1.length() != str2.length())
             return false;
    
    	int map[26] = {0};
    	for(int i = 0; i < str1.length(); ++i)
    		map[str1.at(i)-'a']++;
    
    	for(int i = 0; j < str2.length(); ++i)
    		map[str2.at(i)-'a']--;
    
    	for(int i = 0; i < sizeof(map); ++i)
    		if(map[i] != 0)
    			return false;
    
    	return true
    }

  • 0
    E

    class Solution {
    public:
    bool isAnagram(string s, string t) {
    if(s.length() != t.length())
    return false;

        int map[26] = {0};
        for(int i = 0; i < s.length(); ++i)
        {
            map[s.at(i)-'a']++;
        }
    
        for(int i = 0; i < t.length(); ++i)
        {
            map[t.at(i)-'a']--;
        }
    
        for(int i = 0; i < sizeof(map) / sizeof(int); ++i)
        {
            if(map[i] != 0)
            {
                return false;
            }
        }
    
        return true;
    }
    

    };


Log in to reply
 

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