-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRansomNote.js
More file actions
36 lines (27 loc) · 868 Bytes
/
RansomNote.js
File metadata and controls
36 lines (27 loc) · 868 Bytes
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
// https://leetcode.com/problems/ransom-note/
// Given an arbitrary ransom note string and another string containing
// letters from all magazines, write a function that will return true if
// the ransom note can be constructed from the magazines; otherwise false
/**
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
const expect = require('expect');
function canConstruct(ransomNote, magazine) {
const myObj = {};
magazine.split('').forEach(x => myObj[x] = (myObj[x] || 0) + 1);
ransomNote.split('').forEach(x => myObj[x] = (myObj[x] || 0) - 1);
return Object.keys(myObj).every(x => myObj[x] >= 0);
}
// Test
const testcanConstruct = () => {
expect(
canConstruct('aa', 'aab')
).toEqual(true);
expect(
canConstruct('aa', 'ab')
).toEqual(false);
};
testcanConstruct();
console.log('All tests passed');