只出现一次的字符-Python版

题目描述

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路
采用字典,键为字符,次数为键对应的值。第一次遍历字符串,记录出现次数,第二次遍历字符串,找次数为1的字符,此时返回索引
代码实现
 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     def FirstNotRepeatingChar(self, s):
 4         # write code here
 5         if len(s)==0:
 6             return -1
 7         sdic = {}
 8         for i in s:
 9             if i not in sdic:
10                 sdic[i]=1
11             else:
12                 sdic[i] += 1
13         for j in range(len(s)):
14             if sdic[s[j]]==1:
15                 return j
16         return -1

奇怪的是,使用次数和索引构成的列表作为键的值,在牛客上返回错误,在Python编辑器里面就是正确的

代码如下(在编辑器里面可以,在牛客上不行)

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     def FirstNotRepeatingChar(self, s):
 4         # write code here
 5         if not s:
 6             return -1
 7         sdic = {}
 8         for i in range(len(s)):
 9             if s[i] not in sdic.keys():
10                 temp=[]
11                 temp.append(1)
12                 temp.append(i)
13                 sdic[s[i]]=temp
14             else:
15                 sdic[s[i]][0] +=1
16         for v in sdic.values():
17             if v[0]==1:
18                 return v[1]
19         return -1
原文地址:https://www.cnblogs.com/shuangcao/p/12771789.html