Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions 49_group_anagrams/problem.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
## 問題: [49. Group Anagrams](https://leetcode.com/problems/group-anagrams/description/)
22 changes: 22 additions & 0 deletions 49_group_anagrams/step1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Step 1

- string毎に、アルファベットが何回出たかをa-zの配列に記録する
- dictに配列をキーとする、stringを追加していく
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

「tupleをキー」ですかね(コードを見る感じ)
配列はunhashableです

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

指摘ありがとうございます。
おっしゃる通り、「tupleをキー」です。配列とtupleを同一視していましたが、hash化のことを考えると間違った表現でした。


```python
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
unordered_characters_to_words = defaultdict(list)
for word in strs:
key = [0] * 26
for character in word:
key[ord(character) - ord("a")] += 1
unordered_characters_to_words[tuple(key)].append(word)
return list(unordered_characters_to_words.values())
```

時間計算量: $O(mn)$

空間計算量: $O(mn)$

アルゴリズム最大実行時間(概算): 時間計算量 / Pythonの1秒あたりの計算ステップ数 -> $(10^4 \times 100) \div 10,000,000 = 0.1 (s)$
20 changes: 20 additions & 0 deletions 49_group_anagrams/step2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Step 2

```python
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
signature_to_words = defaultdict(list)
for word in strs:
key = [0] * 26
for character in word:
key[ord(character) - ord("a")] += 1
signature_to_words[tuple(key)].append(word)
return list(signature_to_words.values())

```

時間計算量: $O(mn)$

空間計算量: $O(mn)$

アルゴリズム最大実行時間(概算): 時間計算量 / Pythonの1秒あたりの計算ステップ数 -> $(10^4 \times 100) \div 10,000,000 = 0.1 (s)$
20 changes: 20 additions & 0 deletions 49_group_anagrams/step3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Step 3

```python
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
signature_to_words = defaultdict(list)
for word in strs:
key = [0] * 26
for character in word:
key[ord(character) - ord("a")] += 1
signature_to_words[tuple(key)].append(word)
return list(signature_to_words.values())

```

1回目: 1分 47秒

2回目: 1分 28秒

3回目: 1分 29秒