-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathRansomNote.java
31 lines (29 loc) · 910 Bytes
/
RansomNote.java
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
package io.ziheng.hashtable.leetcode;
import java.util.Map;
import java.util.HashMap;
/**
* LeetCode 383. Ransom Note
* https://leetcode.com/problems/ransom-note/
*/
public class RansomNote {
public boolean canConstruct(String ransomNote, String magazine) {
if (ransomNote == null || magazine == null) {
return false;
}
return canConstructHashing(ransomNote, magazine);
}
public boolean canConstructHashing(String ransomNote, String magazine) {
Map<Character, Integer> aMap = new HashMap<>();
for (char c : magazine.toCharArray()) {
aMap.put(c, 1 + aMap.getOrDefault(c, 0));
}
for (char c : ransomNote.toCharArray()) {
if (!aMap.containsKey(c) || aMap.get(c) <= 0) {
return false;
}
aMap.put(c, aMap.get(c) - 1);
}
return true;
}
}
/* EOF */