题目描述
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序

思路:
1.新建,Map<String,List<String>>
2.遍历字符串数组里的每个字符串
把每个字符串---》字符数组,并对其进行排序
排序后的字符数组--》字符串,作为key,去查找并添加进Map<String,List<String>>
3.最后,输出Map<String,List<String>> 里的所有的value
//遍历字符串数组,对每个字符串用Arrays.sort进行排序,将排序得到的没个结果作为map的key,而value则是一个List
//如果value为空则创建,不为空则把没有排序前的字符串放进去。 最后将Map里的多个value依此存到一个List里即可。
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) return new ArrayList();
Map<String, List> ans = new HashMap<String, List>();
for (String s : strs) {
char[] ca = s.toCharArray();
Arrays.sort(ca);
String key = String.valueOf(ca);
if (!ans.containsKey(key)) ans.put(key, new ArrayList());
ans.get(key).add(s);
}
return new ArrayList(ans.values());
}
}
本文介绍了一种有效的算法,用于将给定字符串数组中的字母异位词进行分组。通过排序每个字符串并将其作为键存储在Map中,实现了快速查找和分组相似字符串的功能。
331

被折叠的 条评论
为什么被折叠?



