本文为Python算法题集之一的代码示例
题目49:字母异位词分组
说明:给你一个字符串数组,请你将 字母异位词 组合在一起,可以按任意顺序返回结果列表
字母异位词 :是由重新排列原单词所有字母得到的新单词
-
使用同步数组
list
和检索集合set
def groupAnagrams_ext1(self, strs): iLen = len(strs) setlist = [] for iIdx in range(iLen): setlist.append(sorted(strs[iIdx])) allset = [] for aSet in setlist: if aSet in allset: continue allset.append(aSet) result=[] for aSetItem in allset: tmpResultItem=[] for iIdx in range(iLen): if setlist[iIdx] == aSetItem: tmpResultItem.append(strs[iIdx]) result.append(tmpResultItem) return result astr = ["eat", "tea", "tan", "ate", "nat", "bat"] print(groupAnagrams_ext1(astr)) # 运行结果 # [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
-
使用同步数组
list
和结果数组list
def groupAnagrams_ext2(self, strs): iLen = len(strs) sortlist = [] for iIdx in range(iLen): sortlist.append(sorted(strs[iIdx])) result, resultsort=[], [] for iIdx in range(iLen): if sortlist[iIdx] in resultsort: result[resultsort.index(sortlist[iIdx])].append(strs[iIdx]) else: resultsort.append(sortlist[iIdx]) result.append([strs[iIdx]]) return result astr = ["eat", "tea", "tan", "ate", "nat", "bat"] print(groupAnagrams_ext2(astr)) # 运行结果 # [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
-
使用字典和元组
def groupAnagrams_ext3(self, strs): from collections import Counter anagrams = {} for s in strs: counter = Counter(s) key = tuple(sorted(counter.items())) if key not in anagrams: anagrams[key] = [] anagrams[key].append(s) return list(anagrams.values()) astr = ["eat", "tea", "tan", "ate", "nat", "bat"] print(groupAnagrams_ext3(astr)) # 运行结果 # [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
一日练,一日功,一日不练十日空文章来源:https://www.toymoban.com/news/detail-809441.html
may the odds be ever in your favor ~文章来源地址https://www.toymoban.com/news/detail-809441.html
到了这里,关于Python算法题集_字母异位词分组的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!