字符串中只出现一次的字符
字符串中第一个只出现一次的字符。
样例:
输入“abaccdeff”
输出“b”
解题思路
通过构建哈希表来实现,定义哈希表的键为字符,而值为字符出现的次数。
hash map
第一次扫描的时间复杂度是
O
(
n
)
O(n)
O(n),第二次扫描读出第一个数字的时间复杂度是
O
(
1
)
O(1)
O(1)。
创建大小为256,以字符ASCII码为键值的哈希表,空间复杂度为
O
(
1
)
O(1)
O(1)。
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
hash_map = [0]*256
for x in s:
hash_map[ord(x)] += 1
for x in s:
if hash_map[ord(x)] == 1:
return s.index(x)
return -1
dictionary
pythonic的写法,涉及到字典底层实现,有空补充。
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
dic = {}
for x in s:
if x in dic:
dic[x] += 1
else:
dic[x] = 1
for x in s:
if dic[x] == 1:
return s.index(x)
return -1
字符流中只出现一次的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。
例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是’g’。
当从该字符流中读出前六个字符”google”时,第一个只出现一次的字符是’l’。
如果当前字符流没有存在出现一次的字符,返回#字符。
样例:
输入:"google"
输出:"ggg#ll"
解释:每当字符流读入一个字符,就进行一次判断并输出当前的第一个只出现一次的字符。
解题思路
依旧是用哈希表来保存相关的信息。
class Solution:
def __init__(self):
self.s = ''
self.dic = {}
def firstAppearingOnce(self):
"""
:rtype: str
"""
for x in self.s:
if self.dic[x] == 1:
return x
return '#'
def insert(self, char):
"""
:type char: str
:rtype: void
"""
self.s += char
if char in self.dic:
self.dic[char] += 1
else:
self.dic[char] = 1