这解法确实思路清奇

零基础刷力扣,第二道题就给我难住了。

389.找不同

给定两个字符串 st ,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

一开始这么写出来:

1
2
3
4
5
char findTheDifference(char* s, char* t) {
int i = 0;
while (strchr(s,t[i])&&i<strlen(t)) i++;
return t[i];
}

但是有一套值死活过不去:

s = {“a”}, t = {“a”,”a”}

之后去解题区发现了个解法惊为天人:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char findTheDifference(char * s, char * t){
int as = 0, at = 0;

while (*s)
as += (*s++);
while (*t)
at += (*t++);

return at - as;

}

作者:Hyy加油
链接:https://leetcode.cn/problems/find-the-difference/solutions/1303319/zhao-bu-tong-by-sharp-7iskov4oc-fmvp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

声明两个变量,分别把集合中的字符以 ASCII 码形式存储在变量中(隐式类型转换),二者之差即是集合相差字符的 ASCII 码。

这玩意我怎么想不到。