题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)
书上的解法是建立hash表,遍历一次字符串计算字符个数,然后再遍历一次查找第一个为1的字符值
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
hashtable=[0]*256#建立hash表
if not s or len(s)>10000:
return -1
for letter in s:
hashtable[ord(letter)]+=1
for letter in s:
if hashtable[ord(letter)]==1:
return s.index(letter)
也可以用python的内置函数解决:
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if not s or len(s)>10000:
return -1
for letter in s:
if s.count(letter)==1:
return s.index(letter)
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
如果当前字符流没有存在出现一次的字符,返回#字符。
注意初始化
# -*- coding:utf-8 -*-
class Solution:
# 返回对应char
def __init__(self):
self.s=""
def FirstAppearingOnce(self):
# write code here
for letter in self.s:
if self.s.count(letter)==1:
return letter
return '#'
def Insert(self, char):
# write code here
self.s+=char