49. 字母异位词分组
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
//先来个正常解法
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) return new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String s : strs) {
char[] ca = s.toCharArray();
Arrays.sort(ca);
String keyStr = String.valueOf(ca);
if (!map.containsKey(keyStr)) map.put(keyStr, new ArrayList<String>());
map.get(keyStr).add(s);
}
return new ArrayList<List<String>>(map.values());
}
}
//当字符串都很长时,排序费时,可以这样优化一下
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ret = new LinkedList<>();
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
String encoded = encode(str);
if (map.containsKey(encoded))
map.get(encoded).add(str);
else {
List<String> list = new LinkedList<>();
list.add(str);
map.put(encoded, list);
}
}
for (Map.Entry<String, List<String>> entry : map.entrySet())
ret.add(entry.getValue());
return ret;
}
private String encode(String str) {
int[] freq = new int[26];
String spliter = "-";
for (int i = 0; i < str.length(); i++)
freq[str.charAt(i) - 'a']++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < freq.length; i++)
sb.append(freq[i]).append(spliter);
return sb.toString();
}
//看起来很牛逼的解法
public List<List<String>> groupAnagrams(String[] strs) {
return new ArrayList<>(Arrays.stream(strs).collect(Collectors.groupingBy(
str ->str.chars().sorted().collect(StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append).toString())).values());
}