-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagram.java
More file actions
92 lines (74 loc) · 2.76 KB
/
Copy pathAnagram.java
File metadata and controls
92 lines (74 loc) · 2.76 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package co.kr.ibeauty;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/*
* TODO
* @Input:String
* @Output ArrayList<ArrayList<String>>
* */
public class Anagram {
//Input text function
public ArrayList<ArrayList<String>> findAnagrams(String sentence) {
//removing all quotes and get anagrams
sentence = sentence.replaceAll("\"", "").replaceAll("\'", "");
return getWordsWithAnagrams(sentence.toLowerCase());
}
//finding anagrams
private ArrayList<ArrayList<String>> getWordsWithAnagrams(String sentence) {
Map<Integer, Map<Integer, String>> map = new HashMap<>();
String[] arr = sentence.split("\\W+", -1);
//finding anagrams
for (int i = 0; i < arr.length; i++) {
int hash = sortStringAndGetHash(arr[i]);
int hash_origin = arr[i].hashCode();
if (hash < 1) continue;
if (!map.containsKey(hash)) {
map.put(hash, addNewItem(hash_origin, arr[i]));
} else if (!map.get(hash).containsKey(hash_origin)) { //checking for repeat word in HashMap
map.get(hash).put(hash_origin, arr[i]);
}
}
return filteringArray(map);
}
//adding new word to HashMap
private Map<Integer, String> addNewItem(int hash_origin, String value){
Map<Integer, String> newItem = new HashMap<>();
newItem.put(hash_origin, value);
return newItem;
}
//sorting word by A-Z and get hashcode
private int sortStringAndGetHash(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray).hashCode();
}
//clearing HashMap from single words,
//switch to ArrayList
private ArrayList<ArrayList<String>> filteringArray(Map<Integer, Map<Integer, String>> map) {
Map<Integer, Map<Integer, String>> _map = new HashMap<>(map);
ArrayList<ArrayList<String>> arr = new ArrayList<>();
Iterator it = _map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
if (map.get(pair.getKey()).size() >= 2){
arr.add(new ArrayList<>(map.get(pair.getKey()).values()));
}
}
return arr;
}
@Test
public void testAnagram() {
String text = "stop post. toaps potrs";
Anagram anagram = new Anagram();
ArrayList<ArrayList<String>> arr = new ArrayList<>();
ArrayList<String> items = new ArrayList<>();
items.add("stop");
items.add("post");
arr.add(items);
Assert.assertEquals(arr, anagram.findAnagrams(text));
}
}