-
Notifications
You must be signed in to change notification settings - Fork 0
/
383.赎金信.js
80 lines (78 loc) · 1.42 KB
/
383.赎金信.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* @lc app=leetcode.cn id=383 lang=javascript
*
* [383] 赎金信
*
* https://leetcode.cn/problems/ransom-note/description/
*
* algorithms
* Easy (64.35%)
* Likes: 324
* Dislikes: 0
* Total Accepted: 173.2K
* Total Submissions: 269.4K
* Testcase Example: '"a"\n"b"'
*
* 给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
*
* 如果可以,返回 true ;否则返回 false 。
*
* magazine 中的每个字符只能在 ransomNote 中使用一次。
*
*
*
* 示例 1:
*
*
* 输入:ransomNote = "a", magazine = "b"
* 输出:false
*
*
* 示例 2:
*
*
* 输入:ransomNote = "aa", magazine = "ab"
* 输出:false
*
*
* 示例 3:
*
*
* 输入:ransomNote = "aa", magazine = "aab"
* 输出:true
*
*
*
*
* 提示:
*
*
* 1 <= ransomNote.length, magazine.length <= 10^5
* ransomNote 和 magazine 由小写英文字母组成
*
*
*/
// @lc code=start
/**
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
var canConstruct = function (ransomNote, magazine) {
let map = {};
// 记录 magazine 中每个字符出现的次数
for (const v of magazine) {
map[v] = (map[v] || 0) + 1;
}
// console.log(map);
for (const v of ransomNote) {
// 抵消 ransomNote 中每个字符的次数
if (map[v]) {
map[v]--;
} else {
return false;
}
}
return true;
};
// @lc code=end