49. 字母异位词分组
- 题号:49
- 来源:LeetCode
- 难度:中等
- 标签:
哈希表字符串排序 - 语言:TypeScript · Python
- 解法:2 个
- 作者:lmliheng
- 最近更新:2026-09-29
TypeScript
TypeScript · O(n*k*log k) 时间 · O(n*k) 空间 · 更新于 2026-09-27
排序后的字符串当哈希键分组
typescript
/**
* @difficulty medium
* @tags 哈希表,字符串,排序
* @time O(n*k*log k)
* @space O(n*k)
* @note 排序后的字符串当哈希键分组
* @49. 字母异位词分组
*/
var groupAnagrams = function (strs: string) {
if (strs.length === 0) {
return [['']]
}
if (strs.length === 1) {
return [[`${strs[0]}`]]
}
let n = 0
let res = []
let map = new Map()
//把排序后的字符串写入map,绑定一个序号
for (let i = 0; i < strs.length; i++) {
let str = strs[i].split('').sort().join('')
if (map.has(str)) {
res[map.get(str)].push(strs[i])
} else {
map.set(str, n)
n++
res.push([strs[i]])
}
}
return res
};Python
Python · O(n*k log k) 时间 · O(n*k) 空间 · 更新于 2026-09-29
排序后的字符串作哈希键分组
python
"""
@difficulty medium
@tags 哈希表,字符串,排序
@time O(n*k log k)
@space O(n*k)
@note 排序后的字符串作哈希键分组
分母异位词分组
lc 49
"""
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
if len(strs)==0:
return [[""]]
if len(strs)==1:
return [[f"{strs[0]}"]]
index=0
s_map={}
res=[]
for str in strs:
new_str=''.join(sorted(str))
print(new_str)
if new_str in s_map:
res[s_map[new_str]].append(str)
else:
s_map[new_str]=index
index+=1
res.append([str])
return res源码:python/leetcode/hot100/2.py
在 GitHub 上查看题目所在目录:lmliheng/algorithm