《劍指offer》35題:找出字符串中第一個(gè)只出現(xiàn)一次的字符眼五,例如abaccdeff
輸出b
普通的每次都查看字符之前有沒(méi)有出現(xiàn)過(guò)的算法復(fù)雜度是O(n^2)
我們用大小為26個(gè)字母(假設(shè)只有字母)的字典或者列表記錄下最早出現(xiàn)的位置和出現(xiàn)的次數(shù)彤灶。
MAX_INDEX = 99999999999
def get_no_repeting_char(str = 'abcdefa'):
hash_table = {}
chars = list(str)
# 字典每個(gè)鍵值都是一個(gè)兩個(gè)元素的列表批旺,列表第一個(gè)是最開始出現(xiàn)的index,第二個(gè)是出現(xiàn)的次數(shù)
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)