阅读目录
题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置,如果没有则返回 -1(需要区分大小写)
思路及Python实现
- 这题和“字符流中第一个只出现一次的字符”题非常像,所以我们同样可以使用字典和队列来做,用字典来记录字符出现的次数,但是字典是无序的,无法保证出现次数为1的字符就是第一个出现的字符,因此,我们可以利用一个队列,来完成,当队首元素出现的次数为1时,那么这个元素一定是第一个只出现一次的,返回位置即可!
# 直接把上次题目的代码拿过来,在队列中添加元素
class Solution:
def __init__(self):
self.memory = {}
self.queue = []
def FirstNotRepeatingChar(self, s):
if not s:
return -1
for item in s:
if item not in self.memory:
self.memory[item] = 0
self.memory[item] += 1
if self.memory[item] == 1: # 出现相同的元素不必重复添加
self.queue.append(item)
while self.queue and self.memory[self.queue[0]] > 1:
self.queue.pop(0)
return s.index(self.queue[0] if len(self.queue) else "")
# 测试
obj = Solution()
s = "google"
print(obj.FirstNotRepeatingChar(s))
也可以这样写,在队列中直接添加索引
class Solution:
def FirstNotRepeatingChar(self, s):
if s == "":
return -1
queue = []
memories = dict()
for index,ss in enumerate(s):
if ss not in memories:
queue.append(index)
memories[ss] = 0
memories[ss] += 1
while queue and memories[s[queue[0]]]>1:
# 找到队首元素所在位置的第一个出现次数为1的元素,返回位置
queue.pop(0)
return queue[0] if queue else -1
# 利用数组建立 哈希表
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if s == ' ':
return -1
hashtable=[0]*256
for i in s:
hashtable[ord(i)] += 1
for i in s:
if hashtable[ord(i)]==1:
return s.index(i)
return -1
# 方法二:利用python自带的字典,两次遍历实现(不建议使用)
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if s==' ':
return -1
d=dict()
#第一次遍历字符串,将每个字符的次数存入字典
for i in s:
d[i]=d.get(i,0)+1
#第二次遍历字符串,检查每个字符出现的次数
for i in s:
if d[i]==1: # O(1)
return s.index(i)
return -1