Skip to content

Commit d92d720

Browse files
authored
简化 1002 查找相同字符 JavaScript版本代码
对两个数组的初值写法进行简化
1 parent f88678d commit d92d720

File tree

1 file changed

+6
-10
lines changed

1 file changed

+6
-10
lines changed

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

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -224,32 +224,28 @@ javaScript
224224
var commonChars = function (words) {
225225
let res = []
226226
let size = 26
227-
let firstHash = new Array(size)
228-
for (let i = 0; i < size; i++) { // 初始化 hash 数组
229-
firstHash[i] = 0
230-
}
227+
let firstHash = new Array(size).fill(0) // 初始化 hash 数组
231228

232229
let a = "a".charCodeAt()
233230
let firstWord = words[0]
234231
for (let i = 0; i < firstWord.length; i++) { // 第 0 个单词的统计
235232
let idx = firstWord[i].charCodeAt()
236233
firstHash[idx - a] += 1
237234
}
238-
235+
236+
let otherHash = new Array(size).fill(0) // 初始化 hash 数组
239237
for (let i = 1; i < words.length; i++) { // 1-n 个单词统计
240-
let otherHash = new Array(size)
241-
for (let i = 0; i < size; i++) { // 初始化 hash 数组
242-
otherHash[i] = 0
243-
}
244-
245238
for (let j = 0; j < words[i].length; j++) {
246239
let idx = words[i][j].charCodeAt()
247240
otherHash[idx - a] += 1
248241
}
242+
249243
for (let i = 0; i < size; i++) {
250244
firstHash[i] = Math.min(firstHash[i], otherHash[i])
251245
}
246+
otherHash.fill(0)
252247
}
248+
253249
for (let i = 0; i < size; i++) {
254250
while (firstHash[i] > 0) {
255251
res.push(String.fromCharCode(i + a))

0 commit comments

Comments
 (0)