diff --git a/387. First Unique Character in a String/387. First Unique Character in a String.md b/387. First Unique Character in a String/387. First Unique Character in a String.md new file mode 100644 index 0000000..6c9efe3 --- /dev/null +++ b/387. First Unique Character in a String/387. First Unique Character in a String.md @@ -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: + 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の中で一番最近のものを取得する。 + 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())) +```