Leetcode 389 找不同
给定两个字符串 s 和 t ,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。
方法一-计数
首先遍历字符串 s, 对其中的每个字符都将计数值加 1 ;然后遍历字符串 t , 对其中的每个字符都将计数值减 1。当发现某个字符计数值为负数时,说明该字符在字符串 t 中出现的次数大于在字符串 s 中出现的次数,因此该字符为被添加的字符。
class Solution {
public:
char findTheDifference(string s, string t) {
//计数
vector<int> vec(26,0);
for(auto ch :s)
{
vec[ch-'a']++; //将字符串s中的 +1
}
for(auto ch : t)
{
vec[ch-'a']--; //将字符串t中的-1(这样出现过的还是0,t中多的那个字母的值会变成-1
if(vec[ch-'a']<0) return ch;
}
return ' ';
}
};
方法二-求和
对字符串s中每一个字符的ascall 求和;对字符串t采取同样的方法,俩者之差就是代表了被添加的字符
class Solution {
public:
char findTheDifference(string s, string t) {
int a =0,b=0;
for(auto ch : s)
{
a+=ch;
}
for(auto ch:t)
{
b+=ch;
}
return b-a;
}
};
方法三-位运算
用位运算找出俩个字符串中出现奇数次的字符
class Solution {
public:
char findTheDifference(string s, string t) {
//位运算
int result = 0;
for(auto ch : s+t)
{
result ^= ch;
}
return result;
}
};