kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 49. Group Anagrams

49. Group Anagrams

Difficulty: Medium

Given an array of strings, group anagrams together.

Example:

1
2
3
4
5
6
7
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

Solution

Language: 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
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
if (strs == null || strs.length == 0) {
return result;
}
Map<String, Integer> indexMap = new HashMap<>();
for (String s : strs) {
String key = genKey(s);
if (!indexMap.containsKey(key)) {
indexMap.put(key, result.size());
result.add(new ArrayList<>());
}
result.get(indexMap.get(key)).add(s);
}
return result;

}

private String genKey(String s) {
char[] a = s.toCharArray();
Arrays.sort(a);
return new String(a);
}
}