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) {
map<char, int> maps;
for (int i = 0; i < s.length(); i++)
{
maps[s[i]]++;
}
for (int i = 0; i < t.length(); i++)
{
maps[t[i]]--;
if (maps[t[i]] < 0)
return t[i];
}
return 0;
}
};
或者是用异或的方法,异或可以用于找到两string之间差异。
class Solution {
public:
char findTheDifference(string s, string t) {
char ans = 0;
if(t.size() <= s.size())
return ans;
for(int i = 0; i < s.size(); ++ i){
ans ^= s[i];
}
for(int i = 0; i < t.size(); ++ i){
ans ^= t[i];
}
return ans;
}
};