First Unique Character in a String
Question
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
Tags
- String
- Hashmap
Thought
Here, we can two sets to record the duplicated and unique characters in the string.
dupSet
: Store the duplicated charactersfirstSet
: Store the unique characters
Code
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dupSet = set()
firstSet = set()
for ch in s:
if ch in dupSet:
continue
if ch in firstSet:
firstSet.remove(ch)
dupSet.add(ch)
else:
firstSet.add(ch)
for i, ch in enumerate(s):
if ch in firstSet:
return i
return -1