Skip to content

387. First Unique Character in a String#15

Open
n6o wants to merge 1 commit intomainfrom
first-unique-character-in-a-string
Open

387. First Unique Character in a String#15
n6o wants to merge 1 commit intomainfrom
first-unique-character-in-a-string

Conversation

@n6o
Copy link
Copy Markdown
Owner

@n6o n6o commented Feb 12, 2026

今回の問題

First Unique Character in a String - LeetCode

使用言語

Go

次に解く問題

Subarray Sum Equals K - LeetCode

Comment on lines +76 to +83
- leetcode の解答
- シンプルに `s` の文字を数えて map に保存する
- rune でも対応可能なので、汎用性が高い
- もう一度 `s` を走査する
- そのときに回数が1であれば、そのときのインデックスが答えとなる
- 走査が終わったら1回しか登場しない文字はなかったということなので -1 を返す
- 時間計算量: O(n)
- 空間計算量: O(1)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

two-passになりますが、コードはかなりシンプルになるので、これはこれでアリだなあと思いました。

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.

ありがとうございます。

そうですね、まず最初に思いつくアルゴリズムとしても自然だと思いました。
(私は思いつかなかったのですが)
複雑なことをまず試しがちなので、「手作業でやってみる」ことから始めるよう練習します。

Copy link
Copy Markdown

@TakayaShirai TakayaShirai left a comment

Choose a reason for hiding this comment

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

全体的に読みやすかったです。時間計算量を求めるだけでなく、具体的な計算時間まで概算されるとさらに良いと思います!

- そのときに回数が1であれば、そのときのインデックスが答えとなる
- 走査が終わったら1回しか登場しない文字はなかったということなので -1 を返す
- 時間計算量: O(n)
- 空間計算量: O(1)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ここの空間計算量が O(1) で想定されているのは、アルファベットのみしか来ないという条件だからでしょうか。

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.

ありがとうございます。

記載いただいている通りで、問題設定で文字種別が固定されているため O(1) としました。
一般化すると 0(n) になると思います。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants