NeetCodeのSolutionを書いていく #
Group Anagrams #
https://neetcode.io/problems/anagram-groups
neetcode.io
問題概要 #
文字列のリストが与えられます。 アナグラムをサブリストにまとめて返しましょう。 リストの順番は問いません。
前提
- 文字列は小文字。
- 配列長は1~1000
- 文字列長は0~100
例 #
Input: strs = [“act”,“pots”,“tops”,“cat”,“stop”,“hat”] Output: [[“hat”],[“act”, “cat”],[“stop”, “pots”, “tops”]]
Input: strs = [“x”] Output: [[“x”]]
Input: strs = [""] Output: [[""]]
メモ #
文字列をソートしてハッシュのキーにすればできそう。 でもそれだとソートの時間がかかっちゃうかな。
とりあえずいけた。 回答もこんな感じではあった。
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
result: Dict = {}
for str in strs:
sorted_str = "".join(sorted(str))
if sorted_str not in result:
result[sorted_str] = [str]
else:
result[sorted_str].append(str)
return list(result.values())