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++
//Hash map
class Solution {
public:
char findTheDifference(string s, string t) {
unordered_map<char, int> m;
for(auto x : s){
m[x]++;
}
for(auto x : t){
m[x]--;
if(m[x] < 0){
return x;
}
}
return 'a';
}
};
//Xor
class Solution {
public:
char findTheDifference(string s, string t) {
char c = 0;
for (char i:s) c ^= i;
for (char i:t) c ^= i;
return c;
}
};
Java
class Solution {
public char findTheDifference(String s, String t) {
char ret = 0;
for(int i = 0; i < s.length(); i++) ret ^= s.charAt(i);
for(int i = 0; i < t.length(); i++) ret ^= t.charAt(i);
return ret;
}
}
Python
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
ret = 0
for c in s:
ret ^= ord(c)
for c in t:
ret ^= ord(c)
return chr(ret)
启示:有关重复元素的题目,优先使用XOR异或解决