《剑指offer》35题:找出字符串中第一个只出现一次的字符,例如abaccdeff
输出b
普通的每次都查看字符之前有没有出现过的算法复杂度是O(n^2)
我们用大小为26个字母(假设只有字母)的字典或者列表记录下最早出现的位置和出现的次数。
MAX_INDEX = 99999999999
def get_no_repeting_char(str = 'abcdefa'):
hash_table = {}
chars = list(str)
# 字典每个键值都是一个两个元素的列表,列表第一个是最开始出现的index,第二个是出现的次数
for index,item in enumerate(chars):
if item in hash_table.keys():
hash_table[item][1] += 1
else:
hash_table[item] = [index,1]
earliest_index = MAX_INDEX
no_repeting_char = None
for key,value in hash_table.items():
# print('{}-{}'.format(key,value))
if value[1] == 1 and value[0] < earliest_index:
earliest_index = value[0]
no_repeting_char = key
return (no_repeting_char,earliest_index)