文章目录
题目描述
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
题解
本题主要作为哈希表的训练题目,解法多为通过寻找对应关系构建哈希表。法一用排序后的字符串作为唯一key,法二用处理过的字符个数字符串为唯一key。
哈希法(java)
思路:
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) {
//抽取key
char[] ca = s.toCharArray();
Arrays.sort(ca);
String key = String.valueOf(ca);
//如果key不存在则新建key
if (!ans.containsKey(key)) ans.put(key, new ArrayList());
//如果key存在则在原key后添加value
ans.get(key).add(s);
}
return new ArrayList(ans.values());
}
}
复杂度分析
- 时间复杂度:
- 空间复杂度:
字母个数法(java)
思路:这个思路会让key变大,比较慢。记下只是提供思路。
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> hash = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
//设置数组存放各字母个数
int[] num = new int[26];
for (int j = 0; j < strs[i].length(); j++) {
num[strs[i].charAt(j) - 'a']++;
}
//转成 0#2#2# 类似的形式
String key = "";
for (int j = 0; j < num.length; j++) {
key = key + num[j] + '#';
}
//
if (hash.containsKey(key)) {
hash.get(key).add(strs[i]);
} else {
List<String> temp = new ArrayList<String>();
temp.add(strs[i]);
hash.put(key, temp);
}
}
return new ArrayList<List<String>>(hash.values());
}
}
- 时间复杂度: 是单个字符串的长度
- 空间复杂度: