387. First Unique Character in a String#15
Open
tNita wants to merge 1 commit into
Open
Conversation
tom4649
reviewed
Mar 27, 2026
| ```Python3 | ||
| class Solution: | ||
| def firstUniqChar(self, s: str) -> int: | ||
| unique_char_poisitions = {} |
| - 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を使っても、辞書の順番は挿入順になる |
nodchip
reviewed
Mar 29, 2026
| ```Python3 | ||
| class Solution: | ||
| def firstUniqChar(self, s: str) -> int: | ||
| char_position = defaultdict(list) |
There was a problem hiding this comment.
この用途であれば、 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] |
There was a problem hiding this comment.
この方針で書くのであれば、 for 文で先頭から回し、 len(v) == 1 のものを return すると、シンプルかつ速くなるかもしれません。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
この問題: First Unique Character in a String
次の問題: Subarray Sum Equals K