From 94bf8916eef21cd40b2eb7b04cf67b2bf32ed6f6 Mon Sep 17 00:00:00 2001 From: Aaron-Lin-74 <84072071+Aaron-Lin-74@users.noreply.github.com> Date: Mon, 7 Mar 2022 10:15:06 +1100 Subject: [PATCH] =?UTF-8?q?Update=201002.=E6=9F=A5=E6=89=BE=E5=B8=B8?= =?UTF-8?q?=E7=94=A8=E5=AD=97=E7=AC=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add TypeScript solution. --- problems/1002.查找常用字符.md | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 7c5566d3..efad1e6a 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -253,6 +253,41 @@ var commonChars = function (words) { return res }; ``` + +TypeScript +```ts +function commonChars(words: string[]): string[] { + let result: string[] = []; + if (words.length === 0) return result; + const size: number = 26; + const hash: number[] = new Array(size).fill(0); + const otherHash: number[] = new Array(size).fill(0); + let pivot: number = 'a'.charCodeAt(0); + // First word + for (let character of words[0]) { + hash[character.charCodeAt(0) - pivot]++; + } + // Other words + for (let i = 1; i < words.length; i++) { + for (let character of words[i]) { + otherHash[character.charCodeAt(0) - pivot]++; + } + // Update the first hash with min + for (let j = 0; j < size; j++) { + hash[j] = Math.min(hash[j], otherHash[j]); + } + // Reset otherHash + otherHash.fill(0); + } + // Construct the result + hash.forEach((element, index) => { + while (element-- > 0) { + result.push(String.fromCharCode(index + pivot)); + } + }); + return result; +} +``` GO ```golang func commonChars(words []string) []string {