本文主要是介绍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] * 26sStart = [0] * 26cnts = 0for c in s:sCnts[ord(c) - ord('a')] += 1if sCnts[ord(c) - ord('a')] == 1:sStart[ord(c) - ord('a')] = cntscnts += 1index = -1for i in range(26):if sCnts[i] == 1 and (index < 0 or index > sStart[i]):index = sStart[i]return index
这篇关于Leetcode 387. First Unique Character in a String的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!