给定一个字符串
S
,如何找到最长且不包含重复字符的子串?如果有多个这样的子字符串具有相同的最大长度,我想返回从左边遇到的第一个。
示例
输入:“wobgrovw”
输出:“bgrovw”
长度:6
def lengthOfLongestSubstring(s: str):
string = ""
length = 0
for c in s:
if c in string:
str_len = len(string)
if length < str_len:
length = str_len
string = string.split(c)[1]+c
else:
string += c
str_len = len(string)
if length < str_len:
length = str_len
print(string)
return length
s = "wobgrovw"
print(lengthOfLongestSubstring(s))
试试这个:
def lengthOfLongestSubstring(s: str):
current_substring = ""
longest_substring = ""
max_length = 0
for c in s:
if c in current_substring:
current_substring = current_substring.split(c, 1)[1] + c
else:
current_substring += c
if len(current_substring) > max_length:
max_length = len(current_substring)
longest_substring = current_substring
print(longest_substring)
return max_length
s = "wobgrovw"
print(lengthOfLongestSubstring(s))