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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# LeetCode

## 問題:
## 問題: [387. First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/description/)

## 前提

Expand Down
26 changes: 24 additions & 2 deletions step1.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
# Step 1

- setとdictを用意する
- 各characterをsetに追加、初見ならdictにインデックスと一緒に追加
- characterが再び現れたらdictから削除
- ループが一周したら、dictでループし最小のインデックスを返す

```python
class Solution:
def firstUniqChar(self, s: str) -> int:
chars = set()
unique_char_to_idx = dict()

for idx, char in enumerate(s):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

こちらのコメントをご参照ください。
hemispherium/LeetCode_Arai60#10 (comment)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

char は他の言語で予約語となっているため、避けたほうが無難かもしれません。 c・ch あたりが良いと思います。

if char in chars:
unique_char_to_idx.pop(char, None)
else:
chars.add(char)
unique_char_to_idx[char] = idx

if len(unique_char_to_idx) == 0:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

辞書の空判定は、

if not unique_char_to_idx:

とするのが良いかもしれません。

参考: https://google.github.io/styleguide/pyguide.html#2144-decision

return -1

return min(unique_char_to_idx.values())
```
時間計算量:

空間計算量:
時間計算量: O(n)

空間計算量: O(n)
15 changes: 15 additions & 0 deletions step2.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,19 @@
# Step 2

- hashを2つ宣言する必要なかった

```python
class Solution:
def firstUniqChar(self, s: str) -> int:
character_to_idx = dict()
n = len(s)

for idx, character in enumerate(s):
if character in character_to_idx:
character_to_idx[character] = n
else:
character_to_idx[character] = idx

res = min(character_to_idx.values())
return -1 if res == n else res
```
20 changes: 17 additions & 3 deletions step3.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
# Step 3

```python
class Solution:
def firstUniqChar(self, s: str) -> int:
character_to_idx = dict()
n = len(s)

for idx, character in enumerate(s):
if character in character_to_idx:
character_to_idx[character] = n
else:
character_to_idx[character] = idx

res = min(character_to_idx.values())
return -1 if res == n else res
```
1回目: 分 秒

2回目: 分 秒
1回目: 1分 53秒

2回目: 1分 54秒

3回目: 分 秒
3回目: 1分 45秒