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 {