C++ solution using bit operations


  • 0
    J
    class Solution { 
    public:
        bool isAnagram(string s, string t) {
          unsigned  int count=0;
          int n1=s.size(),n2=t.size();
          if(n1!=n2) return false; 
          for(int i=0;i<n1;i++) 
              count=count + (1<<(s[i]-'a'))- (1<<(t[i]-'a'));
             
          return count==0;
        }
    }; 
    

    each bit represents a letter, if all bits are cancelled, then bang!


  • 2
    W

    I do not think it's right, suppose "cce" and "ddd", your solution will return true.


  • 0
    J

    you are right!
    I'll close this post then. Thank you very much for pointing it out. Surprisingly it was ACed.


Log in to reply
 

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