-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculate.java
50 lines (47 loc) · 1.68 KB
/
Calculate.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
42
43
44
45
46
47
48
49
50
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Anagram Program
*/
class Anagram {
public static void main(String[] args) {
System.out.println(isAnagram("DIGIT", "GIDIT"));
System.out.println(isAnagram("AAAAAB", "BAACAAA"));
System.out.println(isAnagram("DIGIT", "GIDIT"));
}
public static boolean isAnagram(String word1, String word2) {
Map<Character, Integer> anagramMap1 = new HashMap<>();
Map<Character, Integer> anagramMap2 = new HashMap<>();
int count = 1;
if (!(word1.length() == word2.length())) {
return false;
} else {
for (int i = 0; i < word1.length(); i++) {
if (anagramMap1.containsKey(word1.charAt(i))) {
count = anagramMap1.get(word1.charAt(i)) + 1;
anagramMap1.put(word1.charAt(i), count);
count = 1;
} else {
anagramMap1.put(word1.charAt(i), count);
}
}
for (int i = 0; i < word2.length(); i++) {
if (anagramMap2.containsKey(word2.charAt(i))) {
count = anagramMap2.get(word2.charAt(i)) + 1;
anagramMap2.put(word2.charAt(i), count);
count = 1;
} else {
anagramMap2.put(word2.charAt(i), count);
}
}
for (Map.Entry<Character ,Integer> anagramSet : anagramMap1.entrySet() ){
if (anagramMap2.containsValue(anagramSet.getValue())){
return true;
}
}
}
return false;
}
}