1002.查找共用字符
链接:1002.查找共用字符
难度:Easy
标签:数组、哈希表、字符串
简介:给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
题解 1 - typescript
- 编辑时间:2020-10-14
- 执行用时:120ms
- 内存消耗:41.7MB
- 编程语言:typescript
- 解法介绍:计数。
function commonChars(A: string[]): string[] {
  if (A.length === 0) return [];
  else if (A.length === 1) return A[0].split('');
  const cache: number[] = new Array(26).fill(Infinity);
  const compIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0);
  for (const str of A) {
    const count: number[] = new Array(26).fill(0);
    const addCount = (i: number) => (count[i] = 1 + (count[i] ?? 0));
    for (const c of str) {
      addCount(compIndex(c));
    }
    count.forEach((v, i) => (cache[i] = Math.min(cache[i], v)));
  }
  const ans: string[] = [];
  for (let i = 0; i < 26; i++) {
    const v = cache[i];
    if (v === Infinity) continue;
    new Array(v).fill(0).forEach(_ => ans.push(String.fromCharCode(i + 97)));
  }
  return ans;
}