# [LeetCode] 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.

class Solution {
public:
char findTheDifference(string s, string t) {
unordered_map<char, int> m;
for (char c : s) ++m[c];
for (char c : t) {
if (--m[c] < 0) return c;
}
return 0;
}
};

class Solution {
public:
char findTheDifference(string s, string t) {
char res = 0;
for (char c : s) res ^= c;
for (char c : t) res ^= c;
return res;
}
};

class Solution {
public:
char findTheDifference(string s, string t) {
char res = 0;
for (char c : s) res -= c;
for (char c : t) res += c;
return res;
}
};

class Solution {
public:
char findTheDifference(string s, string t) {
return accumulate(begin(s), end(s += t), 0, bit_xor<int>());
}
};

https://discuss.leetcode.com/topic/55987/java-c-1-liner

https://discuss.leetcode.com/topic/55960/two-java-solutions-using-xor-sum

https://discuss.leetcode.com/topic/55912/java-solution-using-bit-manipulation

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2016-08-28 23:57  Grandyang  阅读(9810)  评论(0编辑  收藏  举报