image

Photo Credit: Pixiv - 七淵

LintCode Solution - Anagrams

http://www.lintcode.com/en/problem/anagrams/

Given an array of strings, return all groups of strings that are anagrams.

Example
Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"].
Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].

Solution 1

Thinking:

  • Using a HashTable to store anagrams (Using the smallest string as a Key)
    • For example: string ba‘s key is ab, and its value is itself, ba.
  • For each string in the input array, calculate its key and store (key, value) into the hashtable with mpa.get(key).add(value). In this case, group anagrams will store in the fomation like key: [abc], value [abc, acb, bca, cba].
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
public class Solution {
/**
* @param strs: A list of strings
* @return: A list of strings
*/

public List<String> anagrams(String[] strs) {
List<String> result = new ArrayList<String>();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();

for (String str : strs) {
char[] key = str.toCharArray();
Arrays.sort(key);

String Key = String.valueOf(key);
if (!map.containsKey(Key)) {
map.put(Key, new ArrayList<String>());
}

map.get(Key).add(str);
}

for (ArrayList<String> tmp : map.values()) {
if (tmp.size() > 1) {
result.addAll(tmp);
}
}

return result;
}
}

Solution 2

Thinking: The key in hashtable for this solution is calculated by getHash()

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
/**
* 本代码由九章算法编辑提供。没有版权欢迎转发。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班
* - 更多详情请见官方网站:http://www.jiuzhang.com/
*/


public class Solution {
private int getHash(int[] count) {
int hash = 0;
int a = 378551;
int b = 63689;
for (int num : count) {
hash = hash * a + num;
a = a * b;
}
return hash;
}

public ArrayList<String> anagrams(String[] strs) {
ArrayList<String> result = new ArrayList<String>();
HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();

for (String str : strs) {
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i) - 'a']++;
}

int hash = getHash(count);
if (!map.containsKey(hash)) {
map.put(hash, new ArrayList<String>());
}

map.get(hash).add(str);
}

for (ArrayList<String> tmp : map.values()) {
if (tmp.size() > 1) {
result.addAll(tmp);
}
}

return result;
}
}