赎金信
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
示例 1:
输入:ransomNote = "a", magazine = "b"
输出:false
1
2
2
var canConstruct = function(ransomNote, magazine) {
if (ransomNote.length > magazine.length) {
return false;
}
const cnt = new Array(26).fill(0);
for (const c of magazine) {
cnt[c.charCodeAt() - 'a'.charCodeAt()]++;
}
for (const c of ransomNote) {
cnt[c.charCodeAt() - 'a'.charCodeAt()]--;
if(cnt[c.charCodeAt() - 'a'.charCodeAt()] < 0) {
return false;
}
}
return true;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var canConstruct = function(ransomNote, magazine) {
if(magazine.length < ransomNote.length) return false
while(ransomNote.length && magazine.length) {
let index = magazine.indexOf(ransomNote[0])
if(index === -1) return false
ransomNote = ransomNote.slice(1, ransomNote.length)
magazine = magazine.slice(0, index) + magazine.slice(index + 1, magazine.length + 1)
}
if(ransomNote.length < 1) return true
return false
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/ransom-note