快樂的LeetCode --- 49. 字母異位詞分組

題目描述:

給定一個字符串數組,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字符串。

示例:

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

解題思路1: 超出時間限制

  1. 通過字符內部的排序,找到不同字母組合的種類
  2. 依次遍歷原有的字符列表,當出現的字母相同時,寫進同一個列表中。

代碼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:

來自LeetCode官方

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()

題目來源:

https://leetcode-cn.com/problems/group-anagrams

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章