O(n) Java solution with constant space, using Bitwise XOR operator 1ms


  • 0
    A
    //O(n) Java solution with constant space, using Bitwise XOR operator. Single pass.
    public class Solution {
        public char findTheDifference(String s, String t) {
            int a = 0, i, l=s.length();
            if (l==0) { 
                if(t.length()==1)return t.charAt(0);
                else return 0;
            }
            a = t.charAt(l);
            for (i=0;i<l;i++){
                a ^= s.charAt(i);
                a ^= t.charAt(i);
            }
            return (char) a;
        }
    }
    

Log in to reply
 

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