给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例 1:
输入:s = “abcd”, t = “abcde”
输出:“e”
解释:‘e’ 是那个被添加的字母。
思路:
将字符串s装入哈希表中并且统计出现次数,遍历字符串t每个字符出现就减去1。如果某个字母对应的值小于0,那就说明这个字母在原来字符串中未出现返回。
class Solution {
public:
char findTheDifference(string s, string t) {
unordered_map<char,int>map;
for(auto c:s){
++map[c];
}
for(int i=0;i<t.size();++i){
if(--map[t[i]]<0)
return t[i];
}
return 0;
}
};
使用位运算也就是异或,原理是0 与 任意字符 异或的结果是 该字符;相同字符 异或的结果是 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;
}
};