49. 字母异位词分组

题目:49. 字母异位词分组

链接:https://leetcode-cn.com/problems/group-anagrams/description/

题目描述嗯写的很清楚了。

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。

我不知道正解啊,瞎写过了。

python:

import collections
def getCntRet(s):
    ret=[]
    for (key,val) in (collections.Counter(s)).items():
        ret.append(str(key)+str(val))
    output=""
    for item in sorted(ret):
        output+=item
    return output
class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        dic=dict()
        for item in strs:
            temp = getCntRet(item)
            # for i in range(len(item)):
            #     temp|=(1<<(ord(item[i])-ord("a")))
            if str(temp) in dic:
                dic[str(temp)].append(item)
            else:
                dic[str(temp)]=[]
                dic[str(temp)].append(item)
        ret=[]
        for (key,val) in dic.items():
            ret.append(val)
        return ret

猜你喜欢

转载自blog.csdn.net/Hilavergil/article/details/80054496