-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagrams_49.java
More file actions
80 lines (67 loc) · 2.44 KB
/
Anagrams_49.java
File metadata and controls
80 lines (67 loc) · 2.44 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
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
/**
* ----------------------------------------------------------------------------
Anagrams
- Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
* ----------------------------------------------------------------------------
*/
/**
* Related: CC150 1.3 & 11.2
*/
/**
* Anagrams: a word or phrase formed by rearranging the letters of another,
* such as cinema, formed from iceman.
*
* This problem looks very simple, however, it is very tricky here
* There are two problems here:
* - 1. How to decide two strings are anagrams &
* - 2. How to group the anagrams
*
* 1. How to decide two strings are anagrams?
* - 1). sorting two strings, and compare whether they are exactly the same
* - O(mlogm) time, where m is the average number of characters
* - 2). HashMap for each string, <char, count>
* - O(m) time & O(set) extra space, where set is the size of charset!
*
* - when length of each string is not large, using sorting is good enough
* - when size of the charset is not large, using hashmap is good enough
*
* 2. How to group the anagrams?
* - 1). two two compare O(n^2), where n is the number of input strings
* - 2). Sorting O(nlongn), anagrams are equal to each other
* - sorting sorted strings
* - 3). Maping: same anagrams are mapped to same group
* - grouping sorted strings
*
* - When using a hashmap in the first step, how to do grouping?
*/
/**
* 1. sorting + 2. HashMap Grouping
*/
public class Solution {
public List<String> anagrams(String[] strs) {
HashMap<String, List<String>> map = new HashMap<>();
List<String> res = new ArrayList<>();
for(String s : strs) {
char[] cs = s.toCharArray();
Arrays.sort(cs);
//XXXX this will return key as cs's mem address!!!!
//String key = cs.toString();
String key = new String(cs);
if (map.containsKey(key))
map.get(key).add(s);
else {
List<String> list = new ArrayList<>();
list.add(s);
map.put(key, list);
}
}
for(List<String> list : map.values()) {
if (list.size() > 1) {
for (String s : list)
res.add(s);
}
}
return res;
}
}