zoukankan      html  css  js  c++  java
  • 387. 字符串中的第一个唯一字符

    给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
    注意:可以假定该字符串只包含小写字母。

    案例:
    s = "leetcode"
    返回 0

    s = "loveleetcode"
    返回 2



    思路:详见注释。
     1 class Solution(object):
     2     def firstUniqChar(self, s):
     3         """
     4         :type s: str
     5         :rtype: int
     6         """
     7         # 初始化一个长为26的列表,用于统计原串中每个字符出现的个数
     8         index = [0] * 26
     9         # print(type(index), type(index[0]))
    10         for i in range(len(s)):
    11             index[ord(s[i])-ord("a")] += 1
    12         for j in range(len(s)):
    13             if index[ord(s[j])-ord("a")] == 1:
    14                 return j
    15         return -1
    16 
    17 
    18 if __name__ == '__main__':
    19     solution = Solution()
    20     print(solution.firstUniqChar("leetcode"))
    21     print(solution.firstUniqChar("loveleetcode"))
    
    
    
     
  • 相关阅读:
    魔术球问题
    【模板】网络最大流
    [SCOI2010]股票交易
    [SCOI2009]生日礼物
    [HAOI2007]修筑绿化带
    [HAOI2007]理想的正方形
    [USACO12MAR]花盆Flowerpot
    滑动窗口
    斐波那契公约数
    [SDOI2008]仪仗队
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12682143.html
Copyright © 2011-2022 走看看