题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路: 用哈希表实现。时间复杂度为O(n)
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if not s:
return -1
tableSize = 256
hashTable = [0]*tableSize
for i in range(len(s)):
hashTable[ord(s[i])]+=1
for i in range(len(s)):
if hashTable[ord(s[i])]==1:
return i
return -1
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
思路:用哈希表来实现。python中可以用字典表示哈希表。ASCII码作为哈希表的键值, 字符出现的次数作为哈希表的值。
# -*- coding:utf-8 -*-
class Solution:
# 返回对应char
def __init__(self):
self.s = ''
self.dict = {}
def FirstAppearingOnce(self):
# write code here
for i in self.s:
if self.dict[i]==1:
return i
return "#"
def Insert(self, char):
# write code here
self.s += char
if char in self.dict:
self.dict[char]+=1
else:
self.dict[char] = 1