Skip to content

387. First Unique Character in a String#15

Open
tNita wants to merge 1 commit into
mainfrom
add/387_first_unique_character_in_a_string
Open

387. First Unique Character in a String#15
tNita wants to merge 1 commit into
mainfrom
add/387_first_unique_character_in_a_string

Conversation

@tNita
Copy link
Copy Markdown
Owner

@tNita tNita commented Mar 27, 2026

```Python3
class Solution:
def firstUniqChar(self, s: str) -> int:
unique_char_poisitions = {}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

細かい点で恐縮ですが、poisitions→positions ですね

- v3.7以降から、辞書の順番は挿入順になるため、自分の案2で行っていたソートは不要
- https://docs.python.org/3/library/stdtypes.html#dict
- > Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
- OrderedDictを使っても、辞書の順番は挿入順になる
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

OrderedDictを知らなかったので勉強になりました。

```Python3
class Solution:
def firstUniqChar(self, s: str) -> int:
char_position = defaultdict(list)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この用途であれば、 collections.Counter も有用だと思います。
https://docs.python.org/3/library/collections.html#collections.Counter

for i, char in enumerate(s):
char_position[char].append(i)

first_unique_positions = [v[0] for k, v in char_position.items() if len(v) == 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.

この方針で書くのであれば、 for 文で先頭から回し、 len(v) == 1 のものを return すると、シンプルかつ速くなるかもしれません。

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.

4 participants