389.找不同
链接:389.找不同
难度:Easy
标签:位运算、哈希表、字符串、排序
简介:给定两个字符串 s 和 t,它们只包含小写字母。字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。请找出在 t 中被添加的字母。
题解 1 - typescript
- 编辑时间:2020-12-18
- 执行用时:96ms
- 内存消耗:40.5MB
- 编程语言:typescript
- 解法介绍:利用哈希表储存。
function findTheDifference(s: string, t: string): string {
  const cache: Record<string, number> = {};
  const setCache = (num: number) => (c: string) => (cache[c] = num + (cache[c] ?? 0));
  const add = setCache(1);
  const minus = setCache(-1);
  for (const c of s) add(c);
  for (const c of t) {
    if (!cache[c]) return c;
    minus(c);
  }
  return '';
}