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.
Example:
Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added.
Subscribe to see which companies asked this question
给出两个都是小写字母的字符串s和t,将s随机组合成一个序列,然后再随机添加一个字母到这个随机序列中,最终组成t字符串,问题:找出t中添加的随机字母
解题思路:
t是由s中的序列加一个字母组成的,所以t中的字母个数必然有一个比s中的字母个数多一个,所以分别找出t中的各个字母有多少个,和s中的字母有多少个,然后一对比即可知道多出来的即为所求
1、设置ans数组,用来记录字母出现的个数,考虑字母a-z是97到122,所以设置ans长度为255即可,并初始化为0,memset(ans,0,sizeof(ans))
2、从0到strlen(t)开始遍历,将ans[t[i]]++,用来记录各个t[i]出现的个数
3、从0到strlen(s)开始遍历,将ans[s[i]]--,上一轮遍历已经知道了所有字母出现的个数,s[i]中每出现一个字母,就将这个出现的减1,最后剩下唯一的一个,即为所求。
4、遍历从0到255,(其实可以从97到122),只要ans[i] ==1,break;此时i即为所求。
代码如下:
char findTheDifference(char* s, char* t) {
int i;
char c;
int ans[255];
memset(ans,0,sizeof(ans));
for(i=0;i<strlen(t);i++)
ans[t[i]] ++;
for(i=0;i<strlen(s);i++)
ans[s[i]] --;
for(i=97;i<122;i++)
if(ans[i] !=0)
break;
return i;
}