题目描述:

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
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> nums(26, 0);
for(int i = 0; i < s.length(); i++){
nums[s[i] - 'a']++;
}
for(int i = 0; i < t.length(); i++){
if(--nums[t[i] - 'a'] < 0) return t[i];
}
return 0;
}
};

还可以使用异或. 由于s与t除了一个元素以外其他都相同, 所以使用0分别于s与t的每个元素异或, 得到的就是多余的那一个字符.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
char findTheDifference(string s, string t) {
char ch = 0;
for(int i = 0; i < s.length(); i++){
ch ^= s[i];
}
for(int i = 0; i < t.length(); i++){
ch ^= t[i];
}
return ch;
}
};