forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnagramsTogether.java
49 lines (41 loc) · 1.33 KB
/
AnagramsTogether.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
package me.ramswaroop.strings;
import java.util.*;
/**
* Created by IntelliJ IDEA.
*
* @author: ramswaroop
* @date: 9/23/15
* @time: 8:11 PM
*/
public class AnagramsTogether {
/**
* Prints all the anagrams together from the string
* array {@param s}.
*
* @param s
*/
public static void printAnagramsTogether(String[] s) {
// each key holds all the indexes of a anagram
HashMap<String, List<Integer>> hashMap = new HashMap<>();
for (int i = 0; i < s.length; i++) {
char[] chars = s[i].toCharArray();
Arrays.sort(chars);
List<Integer> indexes = hashMap.get(String.valueOf(chars));
if (indexes == null) {
indexes = new ArrayList<>();
}
indexes.add(i);
hashMap.put(String.valueOf(chars), indexes);
}
for (Map.Entry<String, List<Integer>> entry : hashMap.entrySet()) {
for (int i = 0; i < entry.getValue().size(); i++) {
System.out.println(s[entry.getValue().get(i)]);
}
System.out.println("------");
}
}
public static void main(String a[]) {
printAnagramsTogether(new String[]{"cat", "dog", "tac", "god", "act"});
printAnagramsTogether(new String[]{"cat", "tac", "act", "god", "dog"});
}
}