-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisAnagram.java
41 lines (33 loc) · 1.15 KB
/
isAnagram.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
32
33
34
35
36
37
38
39
40
41
public class Solution {
static boolean isAnagram(String a, String b) {
// Complete the function
if( a == null || b == null || a.equals("") || b.equals("") )
throw new IllegalArgumentException();
if(a.length() != b.length()){return false;}
a = a.toLowerCase();
b = b.toLowerCase();
//create map
Map<Character, Integer> map = new HashMap<>();
//populating frequencies
for (int k = 0; k < b.length(); k++){
char letter = b.charAt(k);
if( ! map.containsKey(letter)){
map.put( letter, 1 );
} else {
Integer frequency = map.get( letter );
map.put( letter, ++frequency );
}
}
//comparing frequencies
for (int k = 0; k < a.length(); k++){
char letter = a.charAt(k);
if( ! map.containsKey( letter ) )
return false;
Integer frequency = map.get( letter );
if( frequency == 0 )
return false;
else
map.put( letter, --frequency);
}
return true;
}