题目描述:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回-1
思路:
# 遍历字符串,累加到键值为字符串,值为出现次数的字典。
# 然后便利字典的值,为1输出键;遍历结束输出-1
代码实现:
#!/usr/bin/python3
# author lzx
# python实现
# 思路:遍历字符串,累加到键为字符串,值为出现次数的字典。
# 然后遍历字典的值,为1输出键;遍历结束输出-1
def StrFirstIndex(str1):
not_exit = -1
dict1 = {}
for i in str1:
if i in dict1:
dict1[i] += 1
else:
dict1[i] = 1
for key, value in dict1.items():
if value == 1:
return str1.index(key)
break
else:
continue
return not_exit
if __name__ == '__main__':
str1 = input('输入字符串:')
index = StrFirstIndex(str1)
print(index)