File tree 1 file changed +53
-0
lines changed
1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ PROBLEM:
2
+
3
+
4
+ Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that
5
+ will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false .
6
+
7
+ Each letter in the magazine string can only be used once in your ransom note.
8
+
9
+ Note:
10
+ You may assume that both strings contain only lowercase letters.
11
+
12
+ canConstruct (" a" , " b" ) -> false
13
+ canConstruct(" aa" , " ab" ) -> false
14
+ canConstruct(" aa" , " aab" ) -> true
15
+
16
+
17
+ SOLUTION:
18
+
19
+
20
+ class Solution {
21
+ public:
22
+ bool canConstruct (string ransomNote, string magazine) {
23
+
24
+ int i,n1,n2;
25
+ n1=ransomNote.length ();
26
+ n2=magazine.length ();
27
+
28
+ if (n1>n2)
29
+ return false ;
30
+
31
+ unordered_map<char ,int > m;
32
+
33
+ for (i=0 ;i<n2;i++)
34
+ {
35
+ m[magazine[i]]++;
36
+ }
37
+
38
+ for (i=0 ;i<n1;i++)
39
+ {
40
+ if (m[ransomNote[i]]>0 )
41
+ {
42
+ m[ransomNote[i]]--;
43
+ }
44
+ else
45
+ {
46
+ return false ;
47
+ }
48
+ }
49
+
50
+ return true ;
51
+
52
+ }
53
+ };
You can’t perform that action at this time.
0 commit comments