解题思路
题目位置
3.无重复字符的最长子串
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
start=max_len=0
repeat={}
for i in range(len(s)):
if s[i] in repeat and start <= repeat[s[i]]:
start=repeat[s[i]]+1
else:
max_len=max(max_len,i-start+1)
repeat[s[i]]=i
return max_len
模范作业
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_str = ''
max_len = 0
for str in s:
if str not in max_str:
max_str += str
str_len = len(max_str)
max_len = max_len if max_len > str_len else str_len
else:
max_str = max_str[max_str.index(str)+1:]+str
return max_len
我认为这样也是可以的,因为本地pycharm编译可以过,但是在leetcode输出为4,不知道为什么
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_str = ''
max_len = 0
for str in s:
if str not in max_str:
max_str += str
str_len = len(max_str)
max_len = max_len if max_len > str_len else str_len
return max_len
网友评论