LeetCode:387字符串中唯一出现一一次的字符

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.
 

注意事项:您可以假定该字符串只包含小写字母。

 1 class Solution:
 2     def firstUniqChar(self, s: str) -> int:
 3         my_dict = {}
 4         for char in s:      # for 遍历 先把各种字符(作为 Key)中保存到字典之中 对每个字符出现的次数作为 value 保存
 5             if char not in my_dict:
 6                 my_dict[char] = 1
 7             else:
 8                 my_dict[char] += 1
 9         if 1 not in my_dict.values():
10             return -1
11         else:
12             for i in  range(len(s)):
13                 if my_dict[s[i]] == 1:
14                     return i
View Code

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

猜你喜欢

转载自www.cnblogs.com/Halo-zyh-Go/p/12454520.html