This repository has been archived by the owner on Dec 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroupAnagrams.java
78 lines (68 loc) · 1.98 KB
/
GroupAnagrams.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
package com.ematrix;
import java.util.*;
public class GroupAnagrams {
void sort(String[] array) {
HashMap<String,ArrayList<String>> map=new HashMap<>();
for (String s:array){
String sKey=sortChars(s);
if(map.containsKey(sKey)){
map.get(sKey).add(s);
}
else{
ArrayList<String> keyList=new ArrayList();
keyList.add(s);
map.put(sKey,keyList);
}
}
int arayIndex=0;
for(ArrayList item: map.values()){
for(int i=0;i< item.size();i++){
array[arayIndex]=(String) item.get(i);
System.out.println(item.get(i));
arayIndex++;
}
}
}
String sortChars(String s) {
char[] content= s.toCharArray();
Arrays.sort(content);
return new String(content);
}
public static void main(String[] args)
{
GroupAnagrams groupAnagrams=new GroupAnagrams();
// Driver program
String arr[] = { "cat", "dog", "tac", "god", "act" };
groupAnagrams.sort(arr);
}
}
///* Group words by anagram */
// for (String s : array) {
// String newWord= sortChars(s);
// if (map.containsKey(newWord)) {
//
// map.get(newWord).add(s);
// }
// else {
//
// // This is the first time we are
// // adding a word for a specific
// // hashcode
// ArrayList<String> words = new ArrayList<>();
// words.add(s);
// map.put(newWord, words);
// }
// }
//
//
//
// int index = 0;
// for (String key: map.keySet()) {
// ArrayList<String> list= map.get(key);
// for (String t : list) {
// array[index] = t;
// System.out.print(t+" , ");
// index++;
// }
// }
// }