LeetCode-49. Group Anagrams

Given an array of strings, group anagrams together.

For example, given:

1
[“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],

Return:

1
2
3
4
5
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]

Note:

For the return value, each inner list’s elements must follow the lexicographic order.
All inputs will be in lower-case.

思路

将每一个字符串里面的字符进行排序放到HashMap中。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ll = new ArrayList<>();
if (strs.length <= 0) return ll;
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
String sstr = sortStr(str);
if (map.containsKey(sstr)) {
map.get(sstr).add(str);
} else {
List<String> l = new ArrayList<>();
l.add(str);
map.put(sstr, l);
}
}
return new ArrayList<>(map.values());
}

public String sortStr(String str) {
char[] cc = str.toCharArray();
Arrays.sort(cc);
return String.valueOf(cc);
}
}

-------------本文结束感谢您的阅读-------------
Thank you for your encouragement