mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 04:54:51 +08:00
Merge pull request #856 from Jerry-306/patch-42
简化 1002 查找相同字符 JavaScript版本代码
This commit is contained in:
@ -224,10 +224,7 @@ javaScript
|
|||||||
var commonChars = function (words) {
|
var commonChars = function (words) {
|
||||||
let res = []
|
let res = []
|
||||||
let size = 26
|
let size = 26
|
||||||
let firstHash = new Array(size)
|
let firstHash = new Array(size).fill(0) // 初始化 hash 数组
|
||||||
for (let i = 0; i < size; i++) { // 初始化 hash 数组
|
|
||||||
firstHash[i] = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
let a = "a".charCodeAt()
|
let a = "a".charCodeAt()
|
||||||
let firstWord = words[0]
|
let firstWord = words[0]
|
||||||
@ -236,20 +233,19 @@ var commonChars = function (words) {
|
|||||||
firstHash[idx - a] += 1
|
firstHash[idx - a] += 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let otherHash = new Array(size).fill(0) // 初始化 hash 数组
|
||||||
for (let i = 1; i < words.length; i++) { // 1-n 个单词统计
|
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++) {
|
for (let j = 0; j < words[i].length; j++) {
|
||||||
let idx = words[i][j].charCodeAt()
|
let idx = words[i][j].charCodeAt()
|
||||||
otherHash[idx - a] += 1
|
otherHash[idx - a] += 1
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let i = 0; i < size; i++) {
|
for (let i = 0; i < size; i++) {
|
||||||
firstHash[i] = Math.min(firstHash[i], otherHash[i])
|
firstHash[i] = Math.min(firstHash[i], otherHash[i])
|
||||||
}
|
}
|
||||||
|
otherHash.fill(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let i = 0; i < size; i++) {
|
for (let i = 0; i < size; i++) {
|
||||||
while (firstHash[i] > 0) {
|
while (firstHash[i] > 0) {
|
||||||
res.push(String.fromCharCode(i + a))
|
res.push(String.fromCharCode(i + a))
|
||||||
|
Reference in New Issue
Block a user