题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路:
用字典存储每个字符出现的次数,O(n),遍历字符,若字典中对应次数为1 则返回。
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
d = {}
for i in s:
if i not in d:
d[i] = 1
else:
d[i]+= 1
for i in range(len(s)):
if d[s[i]] == 1:
return i
return -1
扩展题目
字符流中第一个不重复的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"
如果当前字符流没有存在出现一次的字符,返回#字符。
思路:
建立一个list,存放只出现一次的字符,如果出现多次就从中删除,该list的首位=第一个出现一次
# -*- coding:utf-8 -*-
class Solution:
# 返回对应char
def __init__(self):
self.s = ''
self.first = [] #存放只出现一次的字符
def FirstAppearingOnce(self):
# write code here
if self.first:
return self.first[0]
return '#'
def Insert(self, char): #字符流
# write code here
self.s+=char
if char not in self.first:
self.first.append(char)
else:
self.first.remove(char)