跳至主要內容

Leetcode: 49. Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”] Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]

Example 2:Input: strs = [“”] Output: [[“”]]

Example 3:Input: strs = [“a”] Output: [[“a”]]

Constraints:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

Since it asks anagram which we can know if we sort the character, then the same anagram must be the same.

Therefore, we can sort the word and look up dictionary.

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        check_dict = {}

        for word in strs:
            sorted_word = str(sorted(word))

            if check_dict.get(sorted_word) is not None:
                check_dict[sorted_word].append(word)
            else:
                check_dict[sorted_word] = [word]

        return check_dict.values()
分類:HashmapLeetcode

搶先發佈留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

由 Compete Themes 設計的 Author 佈景主題