-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
46 lines (35 loc) · 1.1 KB
/
Copy pathGroupAnagrams.java
File metadata and controls
46 lines (35 loc) · 1.1 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
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void groupAnagrams(List<String> anagrams){
HashMap<String, List<String>> anaGroups = new HashMap<String, List<String>>();
for(String word: anagrams){
char[] keyArr = new char[word.length()];
for(int i = 0; i < word.length(); i++){
keyArr[i] = Character.toLowerCase(word.charAt(i));
}
Arrays.sort(keyArr);
String key = new String(keyArr);
if(anaGroups.containsKey(key)){
anaGroups.get(key).add(word);
}
else {
anaGroups.put(key, new ArrayList<String>());
anaGroups.get(key).add(word);
}
}
Set< Map.Entry< String, List<String>>> st = anaGroups.entrySet();
for( Map.Entry<String, List<String>> x: st){
System.out.println(x.getValue());
}
}
public static void main (String[] args) throws java.lang.Exception
{
String[] arr = new String[]{"NonsenSe", "SenseNon", "geeks", "Sgeek"};
groupAnagrams(Arrays.asList(arr));
}
}