forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ransom Note
69 lines (56 loc) · 1.65 KB
/
Ransom Note
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
Ransom Note
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
1 <= ransomNote.length, magazine.length <= 105
ransomNote and magazine consist of lowercase English letters.
Time Complexity -o(n)
Space Complexity -o(n)
Java Solution
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
HashMap<Character,Integer>hmr=new HashMap<Character,Integer>();
HashMap<Character,Integer>hmm=new HashMap<Character,Integer>();
for(int i=0;i<Math.max(ransomNote.length(),magazine.length());i++){
if(i<ransomNote.length())
{
char ch=ransomNote.charAt(i);
if(hmr.get(ch)==null)
hmr.put(ch,1);
else
{
int n=hmr.get(ch);
hmr.put(ch,++n);
}
}
if(i<magazine.length())
{
char ch=magazine.charAt(i);
if(hmm.get(ch)==null)
hmm.put(ch,1);
else
{
int n=hmm.get(ch);
hmm.put(ch,++n);
}
}
}
for(int i=0;i<ransomNote.length();i++){
char ch=ransomNote.charAt(i);
if(hmm.get(ch)==null)
return false;
if(hmr.get(ch)>hmm.get(ch))
return false;
}
return true;
}
}