[Leetcode] 49. Group Anagrams

閱讀時間約 3 分鐘

題目 : 49. Group Anagrams Medium

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"]]


buff : 題目給的list當中的1個字串

buffsorted : 用sorted()重新排列buff字串

solution = {"buffsorted":"buff"}

將buffsorted當作Key,如果有出現過的Key,則在Value中append()buff字串

如果沒有就增加新的Key,assign buff

最後回傳solutions的values即可

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

if len(strs) <1:
return strs
else:
for i in range(len(strs)):
buff = strs[i]
buffsorted = "".join(sorted(buff))
if buffsorted in solution:
solution[buffsorted].append(buff)
else:
solution[buffsorted] = [buff]

return solution.values()








7會員
36內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!
Youna's Devlog 的其他內容
[Leetcode] 242. Valid Anagram
閱讀時間約 3 分鐘
[Leetcode] 217. Contains Duplicate
閱讀時間約 2 分鐘
[Leetcode] 1. Two Sum
閱讀時間約 1 分鐘