File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Given an arbitrary ransom note string and another string containing letters from all the magazines,
2
+ // write a function that will return true if the ransom note can be constructed from the magazines;
3
+ // otherwise, it will return false.
4
+
5
+ // Each letter in the magazine string can only be used once in your ransom note.
6
+
7
+ // Note:
8
+ // You may assume that both strings contain only lowercase letters.
9
+ // canConstruct("a", "b") -> false
10
+ // canConstruct("aa", "ab") -> false
11
+ // canConstruct("aa", "aab") -> true
12
+
13
+ const canConstruct = function ( ransomNote , magazine ) {
14
+ const magazineMap = { } ;
15
+
16
+ for ( const char of magazine ) {
17
+ if ( magazineMap [ char ] ) {
18
+ magazineMap [ char ] ++ ;
19
+ } else {
20
+ magazineMap [ char ] = 1 ;
21
+ }
22
+ }
23
+
24
+ for ( const char of ransomNote ) {
25
+ if ( magazineMap [ char ] > 0 ) {
26
+ magazineMap [ char ] -- ;
27
+ continue ;
28
+ }
29
+ return false ;
30
+ }
31
+ return true ;
32
+ } ;
33
+
34
+ console . log ( canConstruct ( "a" , "b" ) ) // -> false
35
+ console . log ( canConstruct ( "aa" , "ab" ) ) // -> false
36
+ console . log ( canConstruct ( "aa" , "aab" ) ) // -> true
You can’t perform that action at this time.
0 commit comments