diff --git a/49. Group Anagrams.md b/49. Group Anagrams.md new file mode 100644 index 0000000..466ceff --- /dev/null +++ b/49. Group Anagrams.md @@ -0,0 +1,79 @@ +URL: https://leetcode.com/problems/group-anagrams/description/ + +# Step 1 + +- 実装時間: 4分 +- 入力文字列の個数をn、最大の文字列長をmとして + - 時間計算量: O(n * mlogm)。文字列のソートをn回するので。辞書への登録/参照はO(1). + - 空間計算量: O(n) + +```python +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + sorted_str_to_strs = defaultdict(list) + for s in strs: + sorted_string = str(sorted(s)) + sorted_str_to_strs[sorted_string].append(s) + return list(sorted_str_to_strs.values()) +``` + +- `str`や`string`は既存の処理があるので、避けた。スコープも短いし、変数名を`s`にした。 + +# Step 2 + +- 参考にしたURL + - https://github.com/Exzrgs/LeetCode/pull/26 + - https://github.com/fhiyo/leetcode/pull/15 + - https://github.com/nittoco/leetcode/pull/13 + - https://github.com/hayashi-ay/leetcode/pull/19 + - https://github.com/TORUS0818/leetcode/pull/14 + - https://github.com/Ryotaro25/leetcode_first60/pull/13 + - https://github.com/Mike0121/LeetCode/pull/29 + - https://github.com/kazukiii/leetcode/pull/13 + - https://github.com/Yoshiki-Iwasa/Arai60/pull/11 + - https://github.com/rihib/leetcode/pull/3 + - https://github.com/seal-azarashi/leetcode/pull/12 + - https://github.com/hroc135/leetcode/pull/12 + - https://github.com/colorbox/leetcode/pull/26 + - https://github.com/tarinaihitori/leetcode/pull/12 + +- .values()の戻り値がview of the dictionary’s valuesということを知らなかったので確認 + - https://docs.python.org/3/library/stdtypes.html#dict.values + +- `sorted_str_to_strs`はイマイチ。 + - `sorted_str_to_original`とかにする。 + - https://github.com/Exzrgs/LeetCode/pull/26/files#r1622122224 + + +- `str()`は文字列表現を返す。 + - `str(['a', 'e', 't'])`は`['a', 'e', 't']`という文字列を返す。 + - 今回の辞書のキーとして一意なものがたまたまできたが、意図とは違った。 + - https://docs.python.org/3/library/stdtypes.html#str + - やりたいのは`"".join(['a', 'e', 't'])` + - https://docs.python.org/3/library/stdtypes.html#str.join + +```python +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + sorted_str_to_original = defaultdict(list) + for s in strs: + sorted_string = "".join(sorted(s)) + sorted_str_to_strs[sorted_string].append(s) + return list(sorted_str_to_strs.values()) +``` + +# Step 3 + +- 入力文字列の個数をn、最大の文字列長をmとして + - 時間計算量: O(n * mlogm)。 + - 空間計算量: O(n) + +```python +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + sorted_str_to_original = defaultdict(list) + for s in strs: + sorted_string = "".join(sorted(s)) + sorted_str_to_original[sorted_string].append(s) + return list(sorted_str_to_original.values()) +```