给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -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"))