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:
eExplanation:
‘e’ is the letter that was added.
这道题刚开始做的时候并没有理解题目,以为只是简单的数组中插入一个数,就直接用while循环做了,提交的时候不通过才注意到字符串t是字符串s乱序组成的。所以比较简单的思路就是遍历数组后找出多余的那一个字母——我们需要统计一下每个字母出现的频次然后进行比较。
这种统计字母出现频次的题其实已经挺常见了,前些日子做过的字符串快排也有类似的思想。不过这个并不需要建立结构体来分别存放字母和出现频率,直接把字母作为数组下标,出现频次作为其储存值会简单很多。设定数组时只需要把上限设置为 ‘z’+1 即可(数组从零开始)。
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
char findTheDifference(char* s, char* t) {
int i = 0, j = 0;
char sign;
char refer = 'a';
int charNums['z' + 1] = { 0 };
int charNumt['z' + 1] = { 0 };
while (s[i] != 0) {
sign = s[i];
charNums[sign]++;
i++;
}
while (t[j] != 0) {
sign = t[j];
charNumt[sign]++;
j++;
}
while (charNums[refer] == charNumt[refer]) {
refer++;
}
return refer;
}
int main()
{
char s[] = "abcd";
char t[] = "abcde";
printf("%c\n ", findTheDifference(s, t));
return 0;
}
里面还有一个非常重要的地方是数组nums和numt的初值。刚开始做的时候我并没有赋初值,也就导致提交时输出和我本地的输出不一样——可能是因为VS默认的初值为0,而网页编码是随机值,所以为了避免这种情况的出现,我们应该设置时就一并把初值设定为0。
当然除了这个方法外,老哥又提供了一种更为简单的思路:直接比较ACSII值。这种方法来的更为直观,直接统计将字符串中所有字母的ASCII值,相加后求和。然后两个字符串想减所得到的便是多出的那个字母的ASCII值。
简单版代码如下:
char findTheDifference(char* s, char* t) {
char re = 0;
while (*t) {
re += *t - *s;
t++;
s++;
}
return re;
}
嗯,应该是最简单的方法了。