0

I'm doing Leetcode 242. Valid Anagram and here's the 2 basic functions I came up with:

bool isAnagram1(string s, string t) {
        vector<int> countS(26,0), countT(26,0);
        
        for(char c : s){
            countS[c - 'a']++;
        }
        for(char c : t){
            countT[c - 'a']++;
        }
        
        return countS == countT;
    }

bool isAnagram2(string s, string t) {
        int countS[26], countT[26];
        
        for(char c : s){
            countS[c - 'a']++;
        }
        for(char c : t){
            countT[c - 'a']++;
        }
        
        return countS == countT;
       
    }

Basically, I'm wondering why the first solution works but the second one returns a wrong answer. In my mind, these were pretty much the same. I coded the first one after the second one wasn't working. I get no compiler errors. Maybe I'm misunderstanding something about arrays vs vector or the second solution is just plain wrong.

  • 1
    Your `vector` has its values initialized to `0`. Your array doesn't. Incrementing an uninitialized variable is undefined behavior. – Nathan Pierson Jul 14 '22 at 01:40
  • 1
    Replace `int countS[26], countT[26];` with `int countS[26]{}, countT[26]{};` – Jason Jul 14 '22 at 01:43
  • Use `memcmp` to compare contents of C-style arrays. They have semantics inherited from C . – M.M Jul 14 '22 at 02:21

0 Answers0