1、题目描述
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
2、题目分析
- 题目的关键在于如何判断同分异构词
- 刚开始的思路是用字典来判断,但这样复杂度太高,超时
- 使用HashMap来判断,异位词排序后相等,键用排序后的词,值用一个ArrayList来保存
3、代码实现
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
for(int i = 0;i < strs.length;i++){
boolean flag = false;
if(res.size() > 0){
for(int j = 0;j < res.size();j++){
if(isAngagrams(res.get(j),strs[i])){
res.get(j).add(strs[i]);
flag = true;
}
}
}
if(!flag){
res.add(new ArrayList<>());
res.get(res.size() - 1).add(strs[i]);
}
}
return res;
}
private boolean isAngagrams(List<String> list,String s){
int[] l_count = new int[26];
int[] s_count = new int[26];
for(int i = 0;i < list.get(0).length();i++){
l_count[list.get(0).charAt(i) - 'a']++;
}
for(int i = 0;i < s.length();i++){
s_count[s.charAt(i) - 'a']++;
}
for(int i = 0;i < 26;i++){
if(l_count[i] != s_count[i]){
return false;
}
}
return true;
}
}
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,ArrayList<String>> map = new HashMap<>();
for(String s : strs){
char[] ch = s.toCharArray();
Arrays.sort(ch);
String key = String.valueOf(ch);
if(map.containsKey(key)) map.get(key).add(s);
else map.put(key,new ArrayList<>(){{add(s);}});
}
return new ArrayList(map.values());
}
}
4、复杂度分析 /HashMap方法
- 时间复杂度:O(nklogk) ,n是字符串数量,k是字符串的最大长度
- 空间复杂度:O(nk) ,n是字符串数量,k是字符串的最大长度