第2章 面试需要的基础知识
第3章 高质量的代码
第4章 解决面试题的思路
第5章 优化时间和空间效率
面试题39 : 数组中出现次数超过一半的数字
面试题40 : 最小的k个数
面试题42 : 连续子数组的最大和
面试题43 : 从1到n整数中1出现的次数
面试题45 : 把数组排成最小的数
面试题49 : 丑数
面试题50 : 第一个只出现一次的字符、字符流中第一个只出现一次的字符
第6章 面试中的各项能力
第7章 两个面试案例
题目描述
牛客网
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)。
解题思路
建立一个哈希表,第一次扫描的时候,统计每个字符的出现次数。第二次扫描的时候,如果该字符出现的次数为1,则返回这个字符的位置。由于Python3中字典是有序地,所以遇到的第一个次数为1的可立即返回。
实战
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if not s:
return -1
dicts = {}
min_index = len(s)
exist = False
for i in range(len(s)):
if s[i] in dicts:
dicts[s[i]] += 1
else:
dicts[s[i]] = 1
for i in range(len(s)):
if dicts[s[i]] == 1:
return i
return -1
题目描述
牛客网
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
如果当前字符流没有存在出现一次的字符,返回#字符。
解题思路
和上一题一样,都是使用辅助空间存储字符。使用字典存储,key为字符,value为出现的次数。由于Python2中字典是无序的,所以还要用一个列表用于记录字符流的顺序。
实战
class Solution:
# 返回对应char
def __init__(self):
self.dicts = {}
self.lst = []
def FirstAppearingOnce(self):
# write code here
for key in self.lst:
if self.dicts[key] == 1:
return key
return '#'
def Insert(self, char):
# write code here
if char in self.dicts:
self.dicts[char] += 1
else:
self.lst.append(char)
self.dicts[char] = 1