Given two strings
s and
t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
这个题目非常简单,字符串t在包含了s中的所有字符的基础上再加了一个字符,题目要求找出这个被加上的字符。
题意需要注意的一点是字符串t中的字符顺序不一定与s中的相同,要解决这个问题需要两个大小为26的辅助数组,下标0~25分别代表'a'~'z',只需要将两个字符串分别扫一遍,将每个字符串中每个字符出现的次数记录在辅助数组中,然后就可以找到哪个字符在t中出现的次数比s中的多即可解决问题。
以下是源代码:
class Solution {
public:
char findTheDifference(string s, string t) {
int a[26],b[26];
for(int i=0;i<26;i++)
{
a[i]=0;
b[i]=0;
}
char c;
for(int i=0;i<s.size();i++) a[s[i]-'a']++;
for(int i=0;i<t.size();i++) b[t[i]-'a']++;
for(int i=0;i<26;i++)
if(a[i]!=b[i])
{
c='a'+i;
break;
}
return c;
}
};
’