From 3e14c5317f8e56e9f310497cd80599b04b20e29c Mon Sep 17 00:00:00 2001 From: Hiro Funatsuka Date: Thu, 23 Apr 2026 23:38:07 +0900 Subject: [PATCH] Solve first unique character in a string --- README.md | 2 +- step1.md | 26 ++++++++++++++++++++++++-- step2.md | 15 +++++++++++++++ step3.md | 20 +++++++++++++++++--- 4 files changed, 57 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b9c1787..c4f0422 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode -## 問題: +## 問題: [387. First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/description/) ## 前提 diff --git a/step1.md b/step1.md index 54ebbc1..99f4618 100644 --- a/step1.md +++ b/step1.md @@ -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): + 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: + return -1 + + return min(unique_char_to_idx.values()) ``` -時間計算量: -空間計算量: +時間計算量: O(n) + +空間計算量: O(n) diff --git a/step2.md b/step2.md index 6ec3360..2d65ed9 100644 --- a/step2.md +++ b/step2.md @@ -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 ``` diff --git a/step3.md b/step3.md index 522daa6..edd4eee 100644 --- a/step3.md +++ b/step3.md @@ -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秒