Skip to content

Commit

Permalink
Merge pull request youngyangyang04#856 from Jerry-306/patch-42
Browse files Browse the repository at this point in the history
简化 1002 查找相同字符 JavaScript版本代码
  • Loading branch information
youngyangyang04 authored Oct 20, 2021
2 parents 7ade584 + d92d720 commit 77c1098
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions problems/1002.查找常用字符.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,32 +224,28 @@ javaScript
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 firstHash = new Array(size).fill(0) // 初始化 hash 数组

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
}


let otherHash = new Array(size).fill(0) // 初始化 hash 数组
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])
}
otherHash.fill(0)
}

for (let i = 0; i < size; i++) {
while (firstHash[i] > 0) {
res.push(String.fromCharCode(i + a))
Expand Down

0 comments on commit 77c1098

Please sign in to comment.