一、题目介绍
给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入:
s = "abcd"
t = "abcde"
输出:
e
解释:
'e' 是那个被添加的字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-difference
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路
本题重点在于,找到两个字符串中那个不同的字符。本文给出两种方法,详细请见代码。
三、解题代码
//利用异或的相同为0的特性,查找两个字符串中那个唯一不同的字符
class Solution {
public:
char findTheDifference(string s, string t) {
int n = s.size(), i;
char a = s[0] ^ t[0];
for(i = 1; i < n; ++i)
{
a ^= s[i] ^ t[i];
}
a ^= t[i];
return a;
}
};
//利用累加和
class Solution {
public:
char findTheDifference(string s, string t) {
int i, a = 0;
for(i = 0; i < t.size(); ++i)
{
a += t[i];
}
for(i = 0; i < s.size(); ++i)
{
a -= s[i];
}
return a;
}
};