forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnagramsTogetherLexicographically.java
81 lines (69 loc) · 2.47 KB
/
AnagramsTogetherLexicographically.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
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
package me.ramswaroop.strings;
import java.util.*;
/**
* Created by IntelliJ IDEA.
*
* @author: ramswaroop
* @date: 10/11/15
* @time: 7:56 PM
*/
public class AnagramsTogetherLexicographically {
/**
* Takes an array of String {@param s} and prints anagrams in groups where the groups
* are arranged lexicographically and the strings within each group are also arranged
* lexicographically.
*
* @param s
*/
public static void printAnagramsTogether(String[] s) {
HashMap<String, List<Integer>> hashMap = new HashMap<>();
TreeSet<List<String>> treeSet = new TreeSet<>(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof List<?> && o2 instanceof List<?>) {
return ((List<String>) o1).get(0).compareTo(((List<String>) o2).get(0));
} else {
return 0;
}
}
});
for (int i = 0; i < s.length; i++) {
String removeSpaces = s[i].replaceAll("\\s+", "");
char[] chars = removeSpaces.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()) {
List<String> anagrams = new ArrayList<>();
for (int i = 0; i < entry.getValue().size(); i++) {
anagrams.add(s[entry.getValue().get(i)]);
}
Collections.sort(anagrams); // arrange anagrams lexicographically within a single line
treeSet.add(anagrams); // sort the entire output lexicographically
}
Iterator iterator = treeSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
/**
* Take list of strings from console and print anagrams in groups.
*
* @param a
*/
public static void main(String a[]) {
Scanner in = new Scanner(System.in);
List<String> strings = new ArrayList<>();
String s;
// you should use in.hasNextLine()
while (!(s = in.nextLine()).trim().equals("")) {
strings.add(s);
}
printAnagramsTogether(strings.toArray(new String[0]));
}
}