389. Find the Difference*

​https://leetcode.com/problems/find-the-difference/​

题目描述

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.

C++ 实现 1

使用哈希表统计 ​​s​​​ 和 ​​t​​ 中的个数.

class Solution {
public:
char findTheDifference(string s, string t) {

unordered_map<char, int> record;
for (int i = 0; i < s.size(); ++i) {
record[t[i]] ++;
record[s[i]] --;
}
record[t[t.size() - 1]] ++;
char res = '\0';
for (auto &iter : record)
if (iter.second != 0)
res = iter.first;
return res;
}
};

C++ 实现 2

仍然是统计个数.

class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> position(26, 0);
for (int i = 0; i < s.size(); ++ i) {
position[s[i] - 'a'] ++;
position[t[i] - 'a'] --;
}
position[t.back() - 'a'] --;
char res;
for (int i = 0; i < position.size(); ++ i) {
if (position[i] != 0) res = 'a' + i;
}
return res;
}
};

请注意这段代码:

for (int i = 0; i < s.size(); ++ i) {
position[s[i] - 'a'] ++;
position[t[i] - 'a'] --;
}
position[t.back() - 'a'] --;

和 ​​C++ 实现 1​​​ 是不同的, 原因在于在 ​​for​​​ 循环中是先对 ​​s[i]​​​ 进行 ​​++​​​ 操作, 然后对 ​​t[i]​​​ 进行 ​​--​​​ 操作, 之后在 ​​for​​​ 循环外面, 处理 ​​t.back()​​​ 时, 要保证和 ​​for​​​ 循环的处理一致, 即也采用 ​​--​​​ 操作, 如果此时误写为 ​​++​​, 那么会引起 bug.

C++ 实现 3

使用异或操作.

class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> position(26, 0);
char res = '\0';
for (int i = 0; i < s.size(); ++ i) {
res ^= s[i];
}
for (int i = 0; i < t.size(); ++ i) {
res ^= t[i];
}
return res;
}
};