From 7cc60a02a7c62df1784ad9deca39cc7822f0e6e7 Mon Sep 17 00:00:00 2001 From: ltinyho Date: Tue, 3 Aug 2021 10:34:24 +0800 Subject: [PATCH] =?UTF-8?q?1002.=E6=9F=A5=E6=89=BE=E5=B8=B8=E7=94=A8?= =?UTF-8?q?=E5=AD=97=E7=AC=A6-JavaScript=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 40 +++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 875340c4..e3014d00 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -169,6 +169,46 @@ class Solution { } } ``` +javaScript +```js +var commonChars = function (words) { + let res = [] + let size = 26 + let firstHash = new Array(size) + for (let i = 0; i < size; i++) { // 初始化 hash 数组 + firstHash[i] = 0 + } + + let a = "a".charCodeAt() + let firstWord = words[0] + for (let i = 0; i < firstWord.length; i++) { // 第 0 个单词的统计 + let idx = firstWord[i].charCodeAt() + firstHash[idx - a] += 1 + } + + for (let i = 1; i < words.length; i++) { // 1-n 个单词统计 + let otherHash = new Array(size) + for (let i = 0; i < size; i++) { // 初始化 hash 数组 + otherHash[i] = 0 + } + + for (let j = 0; j < words[i].length; j++) { + let idx = words[i][j].charCodeAt() + otherHash[idx - a] += 1 + } + for (let i = 0; i < size; i++) { + firstHash[i] = Math.min(firstHash[i], otherHash[i]) + } + } + for (let i = 0; i < size; i++) { + while (firstHash[i] > 0) { + res.push(String.fromCharCode(i + a)) + firstHash[i]-- + } + } + return res +}; +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)