Skip to content

387. First Unique Character in a String#16

Open
X-XsleepZzz wants to merge 2 commits into
mainfrom
X-XsleepZzz-patch-5
Open

387. First Unique Character in a String#16
X-XsleepZzz wants to merge 2 commits into
mainfrom
X-XsleepZzz-patch-5

Conversation

@X-XsleepZzz
Copy link
Copy Markdown
Owner

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:

Input: s = "leetcode"

Output: 0

Explanation:

The character 'l' at index 0 is the first character that does not occur at any other index.

Example 2:

Input: s = "loveleetcode"

Output: 2

Example 3:

Input: s = "aabb"

Output: -1

Constraints:

1 <= s.length <= 105
s consists of only lowercase English letters.

url: https://leetcode.com/problems/first-unique-character-in-a-string/description/

Added problem description and examples for the First Unique Character in a String.
Added Python implementation for finding the first unique character in a string, including explanations and complexity analysis.
def firstUniqChar(self, s: str) -> int:
char_to_index = {}

for index, char in enumerate(s):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

char は他の言語で予約語となっている場合がありますので、避けたほうが無難だと思います。

continue
char_to_index[char] = index

valid_char_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.

ここでもう一度

for index, char in enumerate(s):

で回して、 char_to_index に int の値が含まれているものを返すという書き方もできそうです。ただ、そうなると、そもそも文字からインデックスへのマッピングを保持するより、それぞれの文字が南海出現したかをカウントして、 1 回のみのものを返す、としたほうがシンプルだとも思います。

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.

2 participants