There is an O(n). Let S
be the string.
Just go through the array with two pointers i
and j
and keep track of number K
of different letters between S[i]
and S[j]
. Increment j
whenever this number is smaller or equal n
and increment i
whenever K
is greater than n
. Also remember the longest substring for which K
was equal to n
.
In the implementation you also need a hash table to keep track of the last occurrence of the letter.
Python implementation:
def longest(S,n):
i = j = K = 0
res = (0,0)
last = {}
while i < len(S):
# if current substring is better than others than save
if K == n and j - i > res[1] - res[0]:
res = (i,j)
# if we reach the end of the string, we're done.
if j + 1 > len(S):
break
# if we can go further with the right end than do it
elif K <= n and j + 1 <= len(S):
if not last.has_key(S[j]):
K = K + 1
last[S[j]] = j
j = j + 1
# if we must go further with the left end than do it
else:
if last.has_key(S[i]):
del last[S[i]]
K = K - 1
i = i + 1
return S[res[0]:res[1]]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…