问题描述:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
输出: [ [“ate”,”eat”,”tea”], [“nat”,”tan”], [“bat”] ]
说明:
所有输入均为小写字母
。不考虑答案输出的顺序
。
问题分析:
方法1:
首先把字符串排序,如果排序后的字符串相同,就放到到一起,可以用Python中的字典实现。
Python3实现:
# @Time :2018/7/16
# @Author :LiuYinxing
class Solution:
def groupAnagrams(self, strs):
res = {}
for item in strs:
k = ''.join(sorted(item)) # 字符串排序
if k not in res: # 判断是否存在
res[k] = []
res[k].append(item) # 相同字符串放到同一个字典 k中
return [res[x] for x in res] # 输出结果
if __name__ == '__main__':
strs = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
solu = Solution()
print(solu.groupAnagrams(strs))
方法2:
上面提到的排序,那么一般排序的时间复杂度,比较好的是N(nlogn),因为题目已经说明,输入的字符串全为小写字符,现在可以桶排序的思想,就是让字符串对号入座,如果相同的位置就加1,这样排序过程时间复杂度N(n),算是一点改进了,根据提交结果来看,并没有快多少,尴尬。
# @Time :2018/7/16
# @Author :LiuYinxing
class Solution:
def groupAnagrams(self, strs):
res = {}
for s in strs:
count = [0] * 26 # 定义桶长
for c in s: # 类似于桶排序的,找号入座,如果已经存在就加一
count[ord(c) - ord('a')] += 1
if tuple(count) not in res:
res[tuple(count)] = []
res[tuple(count)].append(s) # 添加到字典
return list(res.values()) # 返回结果
if __name__ == '__main__':
strs = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
solu = Solution()
print(solu.groupAnagrams(strs))
欢迎指正哦。