题目:
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) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
auto r = mismatch(s.begin(), s.end(), t.begin());
return (*r.second);
}
};
别人的(1):
class Solution {
public:
char findTheDifference(string s, string t) {
// Similar to single number. Can do using hashmap...
int charmap[] = {};
for(char c: t) {
charmap[c-'a']++;
}
// Iterate over s, one letter will have count 1 left
for(char c: s) {
charmap[c-'a']--;
}
for(int i=;i<;i++) {
if (charmap[i] == )
return 'a'+i;
}
return -;
}
};
别人的(2):
class Solution {
public:
char findTheDifference(string s, string t) {
char res = ;
for(auto c: s)
res^=c;
for(auto c: t)
res^=c;
return res;
}
};