给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入: s = "abcd" t = "abcde" 输出: e 解释: 'e' 是那个被添加的字母。
class Solution {
public:
char findTheDifference(string s, string t) {
int ans = 0, i, lens = s.length(), lent = t.length();
for(i = 0; i < lens; i++)
ans ^= (s[i] - 'a');
for(i = 0; i < lent; i++)
ans ^= (t[i] - 'a');
return 'a' + ans;
}
};
根据之前的一道题,当一组书中只有一个出现一次,其他的都出现两次的话,可以用异或找到那个出现一次的数
class Solution {
public:
char findTheDifference(string s, string t) {
int a[26] = {0}, lens = s.length(), lent = t.length(), i;
for(i = 0; i < lens; i++)
a[s[i] - 'a']++;
for(i = 0; i < lent; i++)
if(a[t[i] - 'a'] <= 0)
break;
else
a[t[i] - 'a']--;
return t[i];
}
};
统计出现的对应字母的次数,只出现一次的即为结果