题目描述
给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
计数法
因为元素限定了只能是小写字母,是可以枚举的,所以可以使用元素的ascall码作为索引,出现的次数作为索引对应的值来统计元素在s中出现的次数.
char *arr = malloc(sizeof(sizeof(char) * 26));
for (int index = 0; index < strlen(s);index++) {
arr[s[index] - 'a'] += 1;
}
这样在数组s中出现过的字符串就全部进行了统计.然后只需要在t中进行遍历,查找未出现过的元素即可.这样的元素大概有两种情况:
- 要找的元素从来没有在s中出现过;
- 要找的元素在s中出现过,但是在t中出现的次数多一次;
但无论是哪种情况,只要当前元素对应的索引在arr中对应的值为0,那么该元素就肯定是要找的元素.
for (int index = 0; index < strlen(t); index++) {
unsigned isolateIndex = t[index] - 'a';
if (arr[isolateIndex] == 0) {
return c;
}
arr[t[index] - 'a'] -= 1;
}
// 没啥用就是为了不报错
return '\0';
全部的代码大概这个样子:
char findTheDifference(char * s, char * t){
unsigned length = (unsigned)strlen(s);
char *a = malloc(sizeof(char) * 26) ;
memset(a, 0, sizeof(char) * 26);
for (int index = 0; index < length; index++) {
a[s[index] - 'a'] += 1;
}
for (int index = 0; index < strlen(t); index++) {
if (a[t[index] - 'a'] == 0) {
return t[index];
}
}
return '\0';
}
差集法
数组t比数组s中多一个元素,假如数组数组元素都对应一个唯一的值那么数组就是可以求和的,这样t中元素的和减去s中元素的和,就肯定是多出来的元素的和.
char findTheDifference(char * s, char * t){
char sum = 0;
char *ss = s, *tt = t;
while(*ss != '\0') {
sum += *(tt++) - *(ss++);
}
return (sum + *tt);
}
异或位运算
如果两个数进行异或运算,结果就会为0,依次进行运算那么最后的就过就是出现过基数次的那个元素。
char a = 0;
char *ss = s, *tt = t;
while (*ss) {
a ^= *(ss++) ^ *(tt++);
}
return (char)(a ^ *tt);
这道题的思路与只出现一次的数字具有类似的特点,所以也可以使用异或运算特性来查找:
int singleNumber(int* nums, int numsSize){
int result = 0;
for (int index = 0; index < numsSize; index++) {
result ^= nums[index];
}
return result;
}