题目描述:
给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入:
s = "abcd"
t = "abcde"
输出:e
解释:'e' 是那个被添加的字母。
解题思路:
本题使用枚举的方法比较简单,小写字母只有26种,将连个字符串的每个字母分别统计,很容就找到添加的字母。
这里使用了将字符的ANSCII值,很常见的字符操作手段,能更方便的操作和使用字符以及字符数组。
AC代码:
class Solution {
public:
char findTheDifference(string s, string t)
{
char res;
int ans[256] = { 0 };
for (int i = 0; i < s.length(); i++)
{
ans[s[i]]++;
}
for (int i = 0; i < t.length(); i++)
{
ans[t[i]]--;
}
for (int i = 97; i <= 122; i++)
{
if (ans[i] != 0)
{
res = char(i);
break;
}
}
return res;
}
};