Skip to content

Commit 5992503

Browse files
authored
Update 1160-find-words-that-can-be-formed-by-characters.js
1 parent 63357f5 commit 5992503

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

1160-find-words-that-can-be-formed-by-characters.js

+22-13
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,30 @@
44
* @return {number}
55
*/
66
const countCharacters = function(words, chars) {
7-
const cnt = Array(26)
8-
cnt.fill(0)
9-
for (let c of chars) cnt[c.charCodeAt() - 97]++
10-
11-
let res = 0
12-
for (let word of words) {
13-
let tmp = cnt.slice()
14-
let match = true
15-
for (let c of word) {
16-
if (--tmp[c.charCodeAt() - 97] < 0) {
17-
match = false
7+
let letters = new Array(26).fill(0),
8+
a = 'a'.charCodeAt(0),
9+
z = 'z'.charCodeAt(0)
10+
let count = 0
11+
for (let i = 0; i < chars.length; i++) {
12+
let l = chars[i].charCodeAt(0) - a
13+
letters[l]++
14+
}
15+
for (let i = 0; i < words.length; i++) {
16+
let word = words[i]
17+
let tmp = letters.slice()
18+
let tCount = 0
19+
for (let j = 0; j < word.length; j++) {
20+
let l = word[j].charCodeAt(0) - a
21+
tmp[l]--
22+
if (tmp[l] < 0) {
1823
break
24+
} else {
25+
tCount++
1926
}
2027
}
21-
if (match) res += word.length
28+
if (tCount == word.length) {
29+
count += word.length
30+
}
2231
}
23-
return res
32+
return count
2433
}

0 commit comments

Comments
 (0)