C array[26] simple solution


  • 19
    T

    use array[26] and update the array

    bool isAnagram(char* s, char* t) {
        if(s==NULL && t==NULL) return true;
        if(strlen(s) != strlen(t)) return false;
        
        int a[26]={0};
        for(int i=0;i<strlen(s);i++){
            a[s[i]-'a']++;
            a[t[i]-'a']--;
        }
    
        for(int i=0;i<26;i++){
            if(a[i]<0) return false;
        }
        return true;
    }

  • 1
    Q

    Excellent! My solution was similar but used two 26-character arrays, so it's longer:

    bool isAnagram(char* s, char* t) {
        // Count occurrences of each letter there are in s and t.
        char s_counts[26] = {0};
        char t_counts[26] = {0};
        char *p;
        for (p = s; *p; p++) {
            s_counts[*p-'a']++;
        }
        for (p = t; *p; p++) {
            t_counts[*p-'a']++;
        }
        // If the number of occurrences of each letter are equal,
        // then s and t are anagrams of each other.
        int i;
        for (i = 0; i < 26; i++) {
            if (s_counts[i] != t_counts[i]) {
                return 0;
            }
        }
        return 1;
    }

  • 0
    P

    O(n) solution with map.

    class Solution {

    public:

    bool isAnagram(string s, string t) 
    

    {

       unordered_map<char, int> mymapS, mymapT;
    
        if (s.length() != t.length()) return false;
        for (int i = 0; i < s.length(); ++i){
            ++mymapS[s[i]];
            ++mymapT[t[i]];
        }
        for (int i = 0; i < s.length(); ++i){
            if (mymapS[s[i]] != mymapT[s[i]]) return false;
          //  if (mymapS[t[i]] != mymapT[t[i]]) return false;
        }    
        return true;
    }
    

    };


  • 0
    Z

    My 3 liner C solution with 2 char[26]:

    bool isAnagram(char* s, char* t)
    {
      char hS[26] = {0}, hT[26] = {0};
      while(*s && *t)  (hS[*(s++) -'a'])++, (hT[*(t++) -'a'])++;
      return (!*s && !*t && !memcmp(hS, hT, 26));
    }
    

    Not clearest, but definitly shortest :)


  • 0
    R

    That's a neat solution. Do you know how you would adapt it if there were unicode characters too?

    I'm asking since I have no idea. Thanks.


  • 0
    J

    @qyearsley
    for (p = s; *p; p++) {
    s_counts[*p-'a']++;
    }

    I am new to C. Could anyone please explain what is the loop terminating condition here?
    Thanks!


  • 1
    Z

    @jun711

    valid char array in C (a.k.a c string ) is terminated by null char, '\0'. The loop terminates if pointer p reached the end of the string, because BOOL(*p) == BOOL('\0') == False


  • 1
    C

    this solution is clear,but has a error.
    : Time Limit Exceeded


Log in to reply
 

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