给定一个字符串,找出其中不含有重复字符的最长子串的长度。
生成一个队列,将队列中的字符存于字典中。若下一个字符在字典中已经存在,则从队列中与字典中同时依次删除队尾字符,直至下一个字符不存在于字典中,将该字符添于队首,进行下一次循环。
def get_longest(s):
strings, current_string = {}, ''
max_length, current_length = 0, 0
for index, string in enumerate(s):
if strings.get(string) is not None:
max_length = max(max_length, current_length)
while current_string[0] != string:
strings.pop(current_string[0])
current_string = current_string[1:]
current_length -= 1
strings.pop(current_string[0])
current_string = current_string[1:] + string
strings[string] = index
else:
current_length += 1
current_string += string
strings[string] = index
else:
max_length = max(max_length, current_length)
return max_length
值得注意的是,由于目标字符串可能位于原字符串末端,故在循环结束后还需要更新一次走最大长度。
时间复杂度为
O
(
n
)
O(n)
O(n)。最坏的情况字典
s
t
r
i
n
g
string
string的长度为
n
n
n,故空间复杂度为
O
(
n
)
O(n)
O(n)。