-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagramsOfString.java
More file actions
61 lines (48 loc) · 1.8 KB
/
AnagramsOfString.java
File metadata and controls
61 lines (48 loc) · 1.8 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
/***********************************************************************************
*
* Given an array of strings, return all groups of strings that are anagrams.
* The groups must be created in order of their appearance in the original array.
* Look at the sample case for clarification.
*
* Input:
* N = 5
* words[] = {act,god,cat,dog,tac}
* Output:
* god dog
* act cat tac
* Explanation:
* There are 2 groups of
* anagrams "god", "dog" make group 1.
* "act", "cat", "tac" make group 2.
*
************************************************************************************/
import java.util.*;
public class AnagramsOfString {
public static void main(String[] args) {
AnagramsOfString anagramsOfString = new AnagramsOfString();
String[] words = {"act", "god", "cat", "dog", "tac"};
System.out.println(anagramsOfString.getAnagrams(words));
}
public List<List<String>> getAnagrams(String[] string_list) {
List<List<String>> anagrams = new ArrayList<List<String>>();
Map<String, Integer> map = new HashMap();
int grp = 0;
for (int i = 0; i < string_list.length; i++) {
String s = string_list[i];
char[] arr = s.toCharArray();
Arrays.sort(arr);
System.out.println(arr);
if (map.containsKey(String.valueOf(arr))) {
int index = map.get(String.valueOf(arr));
List<String> targetGroup = anagrams.get(index);
targetGroup.add(s);
} else {
List<String> groups = new ArrayList<>();
groups.add(s);
map.put(String.valueOf(arr), grp++);
anagrams.add(groups);
}
}
return anagrams;
}
}