Skip to content

Commit 7cc60a0

Browse files
authored
1002.查找常用字符-JavaScript版
1 parent 1250c16 commit 7cc60a0

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

problems/1002.查找常用字符.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,46 @@ class Solution {
169169
}
170170
}
171171
```
172+
javaScript
173+
```js
174+
var commonChars = function (words) {
175+
let res = []
176+
let size = 26
177+
let firstHash = new Array(size)
178+
for (let i = 0; i < size; i++) { // 初始化 hash 数组
179+
firstHash[i] = 0
180+
}
181+
182+
let a = "a".charCodeAt()
183+
let firstWord = words[0]
184+
for (let i = 0; i < firstWord.length; i++) { // 第 0 个单词的统计
185+
let idx = firstWord[i].charCodeAt()
186+
firstHash[idx - a] += 1
187+
}
188+
189+
for (let i = 1; i < words.length; i++) { // 1-n 个单词统计
190+
let otherHash = new Array(size)
191+
for (let i = 0; i < size; i++) { // 初始化 hash 数组
192+
otherHash[i] = 0
193+
}
194+
195+
for (let j = 0; j < words[i].length; j++) {
196+
let idx = words[i][j].charCodeAt()
197+
otherHash[idx - a] += 1
198+
}
199+
for (let i = 0; i < size; i++) {
200+
firstHash[i] = Math.min(firstHash[i], otherHash[i])
201+
}
202+
}
203+
for (let i = 0; i < size; i++) {
204+
while (firstHash[i] > 0) {
205+
res.push(String.fromCharCode(i + a))
206+
firstHash[i]--
207+
}
208+
}
209+
return res
210+
};
211+
```
172212

173213
-----------------------
174214
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)

0 commit comments

Comments
 (0)