171. Anagrams

題目

https://www.lintcode.com/problem/anagrams/description?_from=ladder&&fromId=2

實現

  1. 遍歷所有的 word,並對每個 word 排序
  2. 如果排序後的 word 不在 hash 裏,那麼直接 push,否則新建一個 [word]
{
  'word': [xxx, yyy]
}
  1. 最後從 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章