当前位置:   article > 正文

Leetcode 387. First Unique Character in a String

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/277083
推荐阅读
相关标签
  

闽ICP备14008679号