Skip to content

Commit 25cedc7

Browse files
committed
Create 1160.拼写单词.js
1 parent 84c73bd commit 25cedc7

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

1160.拼写单词.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @param {string[]} words
3+
* @param {string} chars
4+
* @return {number}
5+
*/
6+
var countCharacters = function(words, chars) {
7+
function getCode(str, i) {
8+
return str.charCodeAt(i) - 97;
9+
}
10+
11+
const arr = new Array(26).fill(0);
12+
for (let i = 0; i < chars.length; i++) {
13+
arr[getCode(chars, i)]++;
14+
}
15+
16+
let result = 0;
17+
for (let i = 0; i < words.length; i++) {
18+
let j = 0;
19+
while (j < words[i].length) {
20+
arr[getCode(words[i], j)]--;
21+
if (arr[getCode(words[i], j)] < 0) {
22+
break;
23+
}
24+
j++;
25+
}
26+
if (j === words[i].length) {
27+
result += words[i].length;
28+
}
29+
while (j >= 0) {
30+
arr[getCode(words[i], j)]++;
31+
j--;
32+
}
33+
}
34+
return result;
35+
};
36+
37+
console.log(countCharacters(words = ["cat","bt","hat","tree"], chars = "atach"));

0 commit comments

Comments
 (0)