大家好,我是毛毛。ヾ(´∀ ˋ)ノ
那就開始今天的解題吧~
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.判斷strs中的單字,哪些是由相同的字母不同的排列組成的。
想到的方法是把每個strs中的單字做set然後排序,把這個當作這個單字的key存入dictionary中,全部跑完後,取出dictionary的values()
就是答案啦~
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()
今天就到這邊啦~
大家明天見