iT邦幫忙

2022 iThome 鐵人賽

DAY 2
0
自我挑戰組

30天 Neetcode解題之路系列 第 2

Day 2 - 49. Group Anagrams

  • 分享至 

  • xImage
  •  

前言

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
那就開始今天的解題吧~


Question

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.

Think

判斷strs中的單字,哪些是由相同的字母不同的排列組成的。

想到的方法是把每個strs中的單字做set然後排序,把這個當作這個單字的key存入dictionary中,全部跑完後,取出dictionary的values()就是答案啦~

Code

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        #print(set(list(strs[0])))
        
        anagram_dict = {}
        
        for word in strs:
            word_dict = {}
            # 計算字母數量
            for letter in word:
                if letter not in word_dict.keys():
                    word_dict[letter] = 1
                else:
                    word_dict[letter] += 1
            # print("Count: ", word_dict)
            
            # 用排序過後的字母數量(tuple)的list當dictionary的key
            if str(sorted(word_dict.items())) not in anagram_dict.keys():
                value = []
                value.append(word)
                # print("New => ", str(sorted(word_dict.items())), "origin: ", word)
                anagram_dict[str(sorted(word_dict.items()))] = value
            else:
                # print("Existed => ", str(sorted(word_dict.items())), "origin: ", word)
                anagram_dict[str(sorted(word_dict.items()))].append(word)
        
        #print("anagram_dict: ", anagram_dict) 
        return anagram_dict.values()

Submission


今天就到這邊啦~
大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 1 - 前言
下一篇
Day 3 - 242. Valid Anagram
系列文
30天 Neetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言