forked from algorhythms/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
48 lines (43 loc) · 1.19 KB
/
Solution.java
File metadata and controls
48 lines (43 loc) · 1.19 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
47
48
package Anagrams;
import java.util.*;
/**
* User: Danyang
* Date: 1/20/2015
* Time: 11:04
* Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
*/
public class Solution {
/**
* Map and String manipulation
* @param strs
* @return need to understand what to return
*/
public List<String> anagrams(String[] strs) {
Map<String, List<Integer>> map = new HashMap<>();
for(int i=0; i<strs.length; i++) {
String s = sort(strs[i]);
if(!map.containsKey(s)) {
List<Integer> lst = new ArrayList<>();
lst.add(i);
map.put(s, lst);
}
else {
map.get(s).add(i);
}
}
List<String> ret = new ArrayList<>();
for(Map.Entry<String, List<Integer>> e: map.entrySet()) {
if(e.getValue().size()>1) {
for(Integer i: e.getValue())
ret.add(strs[i]);
}
}
return ret;
}
public String sort(String s) {
char [] cs = s.toCharArray();
Arrays.sort(cs);
return new String(cs);
}
}