题目描述:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
解题思路1: 超出时间限制
- 通过字符内部的排序,找到不同字母组合的种类
- 依次遍历原有的字符列表,当出现的字母相同时,写进同一个列表中。
代码1:
class Solution(object):
def groupAnagrams(self, strs):
res = []
if len(strs) <= 1: return [strs]
for i in range(len(strs)):
if ''.join(sorted(strs[i])) not in res:
res.append(''.join(sorted(strs[i])))
temp = []
for j in range(len(res)):
tem = []
for string in strs:
if ''.join(sorted(string)) == res[j]:
tem.append(string)
temp.append(tem)
return temp
解题思路2:
通过将字符串元素列为元组,作为字典的键,从而找出相对应的值来
代码2:
import collections
class Solution(object):
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
解题思路3:
当且仅当每个字符的出现的次数相同时,两个字符串是字母异位词。
代码3:
import collections
class Solution(object):
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
ans[tuple(count)].append(s)
return ans.values()
题目来源: