2017-10-07 15:37:40 +0000   |     algorithm leetcode bit manipulation   |   Viewed times   |    

题目

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

int[26]统计字母频率

代码

class Solution {
    private static int[] freq = new int[26];
    public char findTheDifference(String s, String t) {
        init();
        for (int i = 0; i < s.length(); i++) {
            freq[s.charAt(i)-'a']++;
        }
        for (int i = 0; i < t.length(); i++) {
            if (--freq[t.charAt(i)-'a'] < 0) { return t.charAt(i); }
        }
        return '\0';
    }
    private void init() {
        Arrays.fill(freq,0);
    }
}

结果

find-the-difference-1

^异或操作抵消相同字母

两个相同的字母做^异或操作会互相抵消所有1位的信息。a ^ a = 0

代码

class Solution {
    public char findTheDifference(String s, String t) {
        char c = '\0';
        for (int i = 0; i < s.length(); i++) {
            c ^= s.charAt(i);
            c ^= t.charAt(i);
        }
        return (char)(c ^ t.charAt(t.length()-1));
    }
}

结果

find-the-difference-2