题目描述
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
解题思路:
1.滑动窗口:类似于双指针,参考博文https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/hua-dong-chuang-kou-tu-wen-jiang-jie-by-superychen/
2.动态规划:当遇到重复字符时,则最大长度可能会变,已知它的最长子串长度为Li,如果在Si的末尾追加一个字符C,即Si+1=Si+C,那么length(Si+1)=man(Li,以C为结尾的最长无重复字符串)
代码
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
lookup=[]
cur_len=0
max_len=0
for i in range(len(s)):
val=s[i]
if val not in lookup:
lookup.append(val)
cur_len+=1
else:
index=lookup.index(val)
lookup=lookup[index+1:]
lookup.append(val)
cur_len=len(lookup)
if cur_len>max_len:
max_len=cur_len
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if s == '':
return 0
if len(s) == 1:
return 1
def find_left(s, i):#找s中第i个字符结尾的最大无重复字符串的长度
tmp_str=s[i]
j=i-1
while j>=0 and s[j] not in tmp_str:
tmp_str+=s[j]
j-=1
return len(tmp_str)
length=0
for i in range(len(s)):
length=max(length, find_left(s,i))
return length