-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path383.ransom-note.java
More file actions
39 lines (31 loc) · 1.06 KB
/
Copy path383.ransom-note.java
File metadata and controls
39 lines (31 loc) · 1.06 KB
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
class Solution {
public boolean canConstruct1(String ransomNote, String magazine) {
Map<Character, Integer> count = new HashMap<>();
for (char c : magazine.toCharArray()) {
if (!count.containsKey(c)) {
count.put(c, 0);
}
count.put(c, count.get(c) + 1);
}
for (char c: ransomNote.toCharArray()) {
if (!count.containsKey(c) || count.get(c) == 0) {
return false;
}
count.put(c, count.get(c) - 1);
}
return true;
}
public boolean canConstruct(String ransomNote, String magazine) {
int counts[] = new int[26];
for (char c : magazine.toCharArray()) {
counts[(int)c - (int)'a'] += 1;
}
for (char c: ransomNote.toCharArray()) {
counts[(int)c - (int)'a'] -= 1;
if (counts[(int)c - (int)'a'] < 0) {
return false;
}
}
return true;
}
}