Analysis:
First we need to count the number of occurrences of all characters and their position, and then the position of the characters that appear to be 1, the smallest
Suppose the string is:
' STRINGISASTARINGB '
Solution One:
def first_not_repeating_char (string):
if not string:
return-1
resultdict = {}
to K, s in enumerate ( String):
resultdict [s] = [resultdict [s][0] + 1,k] if resultdict. Get (s) else [1,k]
pos = Len (string)
ret = None for
x in resultdict:
if Resultdict [x][0] ==1 and Resultdict [x][1] <pos:
pos = resultdict [x][1]
ret = (x,pos) return
RET
The data structures involved include the following examples:
Statistical results: {' A ': [2, 9], ' B ': [1,], ' g ': [2,], ' I ': [3], ' n ': [2], ' s ': [3, ten], ' R ': [2, S], ' t ': [2, one]}
Return result: (' B ', 16)
Solution Two:
The use of two dictionaries a number, a storage location;
def first_not_repeating_char (string):
if not string:
return-1
count = {}
loc = {}
for K, s in Enumera Te (string):
count[s] = Count[s] + 1 if count.get (s) Else 1
loc[s] = Loc[s] If Loc.get (s) Else k
pos = Len (stri NG)
ret = None for
k in Loc.keys ():
if Count.get (k) = = 1 and Loc[k] < pos:
pos = loc[k]
ret = (k , Loc[k]) return
RET
The data structures involved include the following examples:
Count {' A ': 2, ' B ': 1, ' G ': 2, ' I ': 3, ' n ': 2, ' s ': 3, ' R ': 2, ' t ': 2}
loc {' A ': 8, ' B ': +, ' G ': 5, ' I ': 3, ' n ': 4, ' ' s ': 7, ' R ': 2, ' t ': 1}
(' B ', 16)