You are 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 = "neetcodeislove"
Output: 0Explanation: The character 'n' at index 0 is the first character that does not occur at any other index.
Example 2:
Input: s = "neetcodeneet"
Output: 4Example 3:
Input: s = "baab"
Output: -1Constraints:
1 <= s.length <= 1,00,000s consists of only lowercase English letters.class Solution:
def firstUniqChar(self, s: str) -> int:
for i in range(len(s)):
flag = True
for j in range(len(s)):
if i == j:
continue
if s[i] == s[j]:
flag = False
break
if flag:
return i
return -1class Solution:
def firstUniqChar(self, s: str) -> int:
count = defaultdict(int)
for c in s:
count[c] += 1
for i, c in enumerate(s):
if count[c] == 1:
return i
return -1class Solution:
def firstUniqChar(self, s: str) -> int:
n = len(s)
count = defaultdict(int)
for i, c in enumerate(s):
if c not in count:
count[c] = i
else:
count[c] = n
res = n
for c in count:
res = min(res, count[c])
return -1 if res == n else resclass Solution:
def firstUniqChar(self, s: str) -> int:
res = n = len(s)
for ch in range(ord('a'), ord('z') + 1):
index = s.find(chr(ch))
if index != -1 and s.rfind(chr(ch)) == index:
res = min(res, index)
return -1 if res == n else res