# 389. 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 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation