題目描述:
給定一個字符串數組,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字符串。
示例:
輸入: ["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()
題目來源: