Leetcode 387. First Unique Character in a String
Problem
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Algorithm
Use two lists: one list is used to count the letters in “s”; the other list is the position where the letter first appears. Then find the smallest position of the letters appear once.
Code
class Solution:
def firstUniqChar(self, s: str) -> int:
sCnts = [0] * 26
sStart = [0] * 26
cnts = 0
for c in s:
sCnts[ord(c) - ord('a')] += 1
if sCnts[ord(c) - ord('a')] == 1:
sStart[ord(c) - ord('a')] = cnts
cnts += 1
index = -1
for i in range(26):
if sCnts[i] == 1 and (index < 0 or index > sStart[i]):
index = sStart[i]
return index