Through about the Q, I find mistake in my A.


  • 0
    A

    For this question, we can see the description "to determine if (string)t is an anagram of (string)s".emmm...
    If I understand it correctly, it means that the two string are consist of the same letter.
    Their size are same, any letter appears the same times.
    So we can use the XOR to solve it.
    the following:

    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        int x = 0;
        for (char c: s)
            x ^= c;
        for (char c: t)
            x ^= c;
        return x == 0;
    }
    

    But...
    I write a couple data "[aaaaab], [aaabbb]". If XOR, it return true, because in XOR, [aaaaab]=[ab]=[aaabbb], so we cannot use XOR.

    Then I think "+-" maybe a good choise, so I write code like that:

    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        int x = 0;
        for (int i = 0; i < s.size(); i++)
            x += s[i];
        for (int i = 0; i < t.size(); i++)
            x -= t[i];
        return x == 0;
    }
    

    Now you can see...Though the letters' ASCII is diff, two letters' sum may the same.
    the following:

       (ASCII)[ac]=(ASCII)[bb]
    

    So after the analysis, XOR or "+-" cannot use here. we can write like :

    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s==t;
    }
    

    or take it out by unordered_map<char, int>, store the first string in the map, use the second string to reduce the val of key.


Log in to reply
 

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