Skip to content

Commit cd787ce

Browse files
committed
383. 赎金信
1 parent bc9c3eb commit cd787ce

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@
7878
|344|[反转字符串](https://leetcode-cn.com/problems/reverse-string/)|[JavaScript](./algorithms/reverse-string.js)|Easy|
7979
|349|[两个数组的交集](https://leetcode-cn.com/problems/intersection-of-two-arrays/)|[JavaScript](./algorithms/intersection-of-two-arrays.js)|Easy|
8080
|350|[两个数组的交集 II](https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/)|[JavaScript](./algorithms/intersection-of-two-arrays-ii.js)|Easy|
81+
|383|[赎金信](https://leetcode.cn/problems/ransom-note/)|[JavaScript](./algorithms/ransom-note.js)|Easy|
8182
|387|[字符串中的第一个唯一字符](https://leetcode-cn.com/problems/first-unique-character-in-a-string/)|[JavaScript](./algorithms/first-unique-character-in-a-string.js)|Easy|
8283
|389|[找不同](https://leetcode.cn/problems/find-the-difference/)|[JavaScript](./algorithms/find-the-difference.js)|Easy|
8384
|396|[旋转函数](https://leetcode.cn/problems/rotate-function/)|[JavaScript](./algorithms/rotate-function.js)|Medium|

algorithms/ransom-note.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* @param {string} ransomNote
3+
* @param {string} magazine
4+
* @return {boolean}
5+
*/
6+
var canConstruct = function (ransomNote, magazine) {
7+
// 数组哈希计数
8+
const countArr = Array(26).fill(0);
9+
10+
for (let char of magazine) {
11+
const index = char.charCodeAt() - "a".charCodeAt();
12+
countArr[index]++;
13+
}
14+
15+
for (let char of ransomNote) {
16+
const index = char.charCodeAt() - "a".charCodeAt();
17+
countArr[index]--;
18+
19+
if (countArr[index] < 0) {
20+
return false;
21+
}
22+
}
23+
24+
return true;
25+
26+
// 哈希表
27+
// const map = new Map();
28+
29+
// for (let char of magazine) {
30+
// if (map.has(char)) {
31+
// const count = map.get(char);
32+
// map.set(char, count + 1);
33+
// } else {
34+
// map.set(char, 1);
35+
// }
36+
// }
37+
38+
// for (let char of ransomNote) {
39+
// if (map.has(char)) {
40+
// const count = map.get(char);
41+
// if (count - 1 < 0) {
42+
// return false;
43+
// } else {
44+
// map.set(char, count - 1);
45+
// }
46+
// } else {
47+
// return false;
48+
// }
49+
// }
50+
51+
// return true;
52+
};

0 commit comments

Comments
 (0)