First Unique Character in a String
Given a string s, find the first non-repeating character and return its index. Return -1 if no such character exists.
Example
leetcode
0
- Input:
sis the stringleetcode, eight lowercase letters at positions through : l, e, e, t, c, o, d, e. - Which letters repeat: "e" occurs times (positions , and ). Every other letter, namely l, t, c, o and d, occurs exactly once.
- Candidates: the non-repeating letters sit at positions . A letter qualifies only by its count across the whole string, so "e" at position is ruled out even though its later copies come after it.
- Output: the smallest candidate position is (the letter "l"), so the answer is
0, an index, not the character itself. - Notice: "first" means earliest in the string, not alphabetically first ("c" would win alphabetically). If every letter repeats, as in "aabb", there is no candidate and the answer is .
Constraints
- 1 <= len(s) <= 10^5
- s consists of lowercase English letters