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:

1
2
3
4
5
6
7
8
9
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.


方法1:HashMap

最直观的做法是统计s中每个字符出现的次数,然后在扫描t,把相应字符的counter–, 如果减过之后,counter == -1,那就说明这个字就是所要找的字符

1
2
3
4
5
6
7
8
9
10
11
public char findTheDifference(String s, String t) {
int[] count = new int[26];
for(char c : s.toCharArray()) {
count[c - 'a']++;
}
for(char c : t.toCharArray()) {
if(--count[c - 'a'] < 0)
return c;
}
return ' ';
}

方法2: bit manipulation

这个题目很像136. Single Number, 如果把字符看成数字,s和t中除了所求字符外,所有的字符都出现了两次。所求字符就是Single Number.

1
2
3
4
5
6
7
8
public char findTheDifference(String s, String t) {
char result = 0;
for (char c : s.toCharArray())
result ^= c;
for (char c : t.toCharArray())
result ^= c;
return result;
}