题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)
思路
- 将字符串按照每个字符及出现的次数放入字典中
- 遍历字典,找到只出现一次的字符位置。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.dict={}
def FirstNotRepeatingChar(self, s):
# write code here
if not s:
return -1
for i in s:
if i not in self.dict:
self.dict[i]=1
else:
self.dict[i]+=1
#求的是字符串的位置,用字符串的索引来做循环,遍历字典
for i in range(len(s)):
if self.dict[s[i]]==1:
return i
return -1
测试用例
if __name__=='__main__':
s=Solution()
ss="abcab"
print(s.FirstNotRepeatingChar(ss))