0ms C++solution,O(n)time


  • 19
      bool isAnagram(string s, string t) {
        int alp[26]={};
        for (int i = 0; i < s.length(); i++) 
            alp[s.at(i) - 'a']++;
        for (int i = 0; i < t.length(); i++)
            alp[t.at(i) - 'a']--;
        for (int i=0;i<26;i++)
            if (alp[i] != 0) 
                return false;
            return true;
       }

  • 0

    I wrote exactly like this and 16ms.
    By the way, I just wrote
    "int alp[26]"
    instead of
    "int alp[26]={};"
    and it caught me an error when s = t = " ". Could you help me explain this please? Thanks.


  • 0

    alp[26]={} means every element is 0, like alp[26]={0}. if you do not initialize this array, the element may not be 0, if the test string do not contain the 26 different letters, some elements in the array alp may not change. so the judge statement if (alp[i] != 0) could not make the right judgment.


  • 0

    Oh I see. Thanks!


  • 0
    Z

    bool isAnagram(string s, string t) {

        unordered_map<char,int> Mymap;
        int m=s.length();
        int n=t.length();
        
        if(m!=n)
        return false;
        
        for(int i=0;i<m;i++)
        {
            if(Mymap.find(s[i])==Mymap.end())
                Mymap[s[i]] = i+100;
            else
                Mymap[s[i]] += 100;
        }
        
        for(int i=0;i<n;i++)
        {
            if(Mymap.find(t[i])==Mymap.end())
                return false;
                
            else if((Mymap[t[i]] -= 100)<0)
                return false;
                
        }
        
        return true;

  • 0
    Z
    This post is deleted!

  • 0
    O

    It seems that your program runs 16ms , how to get 0 ms? or 8ms ? Thank you.


Log in to reply
 

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