Two Java solutions using different techniques


  • 0
    L

    It is a standard example for using XOR since all matching values cancel out. Here is the code using XOR

     public char findTheDifference(String s, String t) {
            char c = '\u0000';
            for(int i=0,j=0;i<s.length()|| j<t.length() ;) {
                if(i<s.length()) {
                    c ^=s.charAt(i++);
                }
                if(j<t.length()) {
                    c ^=t.charAt(j++);
                }
            }
            return c;       
        }
    

    Another example is to use truth table.

    public char findTheDifference(String s, String t) {
            int[] table = new int[26];
            for(char c : s.toCharArray()) {
                table[c-'a']++;
            }
            
            for(char c : t.toCharArray()) {
                table[c-'a']--;
            }
            
            for(byte i=0;i<26;i++) {
                if(table[i]<0) {
                    return (char)(i+'a');
                }
            }
            return '\u0000';        
        }
    

Log in to reply
 

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