O(n) java solution with Unicode, using bit manipulation


  • 0
    A
    1. like a switch, using XOR to turn on/off bit
    2. sum of each string should be the same. strings should have same characters.
    3. even the same, it may have case like "xaaddy" and "xbbccy",
      need to make sure each string is using the same bit.
      then "OR" is used.
    public class Solution {
        public boolean isAnagram(String s, String t) {
            int size = s.length();
            if (size != t.length()) return false;
            
            int xor = 0;
            int sum = 0;
            int orA = 0;
            int orB = 0;
            for (int i = 0; i < size; i++)
            {
                char c1 = s.charAt(i);
                char c2 = t.charAt(i);
                xor ^= c1;
                xor ^= c2;
                sum += c1;
                sum -= c2;
                orA |= c1;
                orB |= c2;
            }
            if ((xor != 0) || (sum != 0) || (orA != orB)) return false;
            return true;
        }
    }
    

Log in to reply
 

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