赞
踩
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
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.
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。