題目來源
兩個字符串,只有一個字符的差別,不過順序有點亂,讓你找出那個字符,我想到的是用哈希,記錄下各有多少個字符,比較一下,需要遍歷兩個字符串各一次,遍歷長度26的數(shù)組一次,感覺應該夠好了吧。
代碼如下:
class Solution {
public:
char findTheDifference(string s, string t) {
int map1[26] = {0}, map2[26] = {0};
auto n1 = s.size();
for (auto i=0; i<n1; i++) {
map1[s[i]-'a']++;
map2[t[i]-'a']++;
}
map2[t[n1]-'a']++;
for (int i=0; i<26; i++)
if (map1[i] != map2[i])
return char('a'+i);
return 'a';
}
};
然后看了討論區(qū),果然又被打臉了。
直接看代碼吧。
class Solution {
public:
char findTheDifference(string s, string t) {
auto n1 = s.size();
char res = t[n1];
for (auto i=0; i<n1; i++) {
res ^= s[i];
res ^= t[i];
}
return res;
}
};