forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnagramsTogether.java
54 lines (46 loc) · 1.62 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
50
51
52
53
54
package com.rampatra.strings;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 9/23/15
*/
public class AnagramsTogether {
/**
* Prints all the anagrams together from the string array {@code strings}.
* <p/>
* Anagrams are words consisting of the same letters but in the same or different
* order. For example, "cat" and "tac" are anagrams. Same as "god" and "dog".
*
* @param strings
*/
private static void printAnagramsTogether(String[] strings) {
// each key holds all the indexes of a anagram
HashMap<String, List<Integer>> hashMap = new HashMap<>();
for (int i = 0; i < strings.length; i++) {
char[] chars = strings[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(strings[entry.getValue().get(i)]);
}
System.out.println("------");
}
}
public static void main(String[] args) {
printAnagramsTogether(new String[]{"cat", "dog", "tac", "god", "act"});
printAnagramsTogether(new String[]{"cat", "tac", "act", "god", "dog"});
}
}