題目
https://www.lintcode.com/problem/anagrams/description?_from=ladder&&fromId=2
實現
- 遍歷所有的 word,並對每個 word 排序
- 如果排序後的 word 不在 hash 裏,那麼直接 push,否則新建一個
[word]
{
'word': [xxx, yyy]
}
- 最後從 hash 裏拿所有 length 大於 2 的數組,再拼接起來
代碼
class Solution:
"""
@param strs: A list of strings
@return: A list of strings
"""
def anagrams(self, strs):
if strs is None:
return []
dict = {}
for word in strs:
sorted_word = ''.join(sorted(word))
if sorted_word not in dict:
dict[sorted_word] = [word]
else:
dict[sorted_word] += [word]
results = []
for sorted_word in dict:
if len(dict[sorted_word]) >= 2:
results += dict[sorted_word]
return results