Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
https://leetcode.com/problems/first-unique-character-in-a-string/description/

## STEP 1
カウンターで頻度を取っておいて、次は先頭から頻度が1のものを探す。
```python
from collections import Counter
class Solution:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

PEP8

Surround top-level function and class definitions with two blank lines.

とあるように、class と import 文の間に2つ空行を入れる方が一般的かと思います。

def firstUniqChar(self, s: str) -> int:
counter = Counter(s)
for index, char in enumerate(s):
if counter[char] == 1:
return index
return -1
```

## STEP 2
Linked Hashmapを使っても解けるみたい。順序を保持するhashmapに今の所1回しか登場していない文字と場所を記録し、すでに出現した文字をhashsetに記録する。2回目が現れたらhashmapから消して、最後にhashmapの中で一番最近のものを取得する。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: dict の挿入順が保持されることを利用しているのですね。一番最近のものを取得というより、最初に挿入されたものを取得、とした方が誤解がないかもしれません。

https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.hdbcrwo3urck
```python
class Solution:
def firstUniqChar(self, s: str) -> int:
unique_char_to_index = {}
seen_chars = set()
for i, c in enumerate(s):
if c in unique_char_to_index:
del unique_char_to_index[c]
continue
if c in seen_chars:
continue
seen_chars.add(c)
unique_char_to_index[c] = i
if not unique_char_to_index:
return -1
return next(iter(unique_char_to_index.values()))
```
## STEP 3
STEP2の方針で練習。
```python
class Solution:
def firstUniqChar(self, s: str) -> int:
seen = set()
unique_char_to_index = {}
for i, c in enumerate(s):
if c in unique_char_to_index:
del unique_char_to_index[c]
continue
if c in seen:
continue
seen.add(c)
unique_char_to_index[c] = i
if not unique_char_to_index:
return -1
return next(iter(unique_char_to_index.values()))
```