-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidAnagram.java
More file actions
33 lines (27 loc) · 942 Bytes
/
validAnagram.java
File metadata and controls
33 lines (27 loc) · 942 Bytes
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
import java.util.HashMap;
class validAnagram {
public static boolean validAnagram(String s, String t) {
// make freq map of s
// for each char in t, check if in s
// create count, subtract
HashMap<Character, Integer> sFreq = new HashMap<>();
for (Character c : s.toCharArray()) {
sFreq.put(c, sFreq.getOrDefault(c, 0) +1);
}
System.out.println("sFreq: " + sFreq);
for (Character c : t.toCharArray()) {
if (!sFreq.containsKey(c)) return false;
// get the freq of c in the hash
int count = sFreq.get(c);
if (count <= 0) return false;
// subtract c from the hash
sFreq.put(c, count - 1);
}
return true;
}
public static void main(String[] args) {
String s = "abc";
String t = "abd";
System.out.println(validAnagram(s, t));
}
}