一.最长不重复字符子串长度
题目描述
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
思路分析
滑动窗口双指针
1.初始化头尾指针 head,tail;
2.tail 指针右移,判断 tail 指向的元素是否在 [head:tail] 的窗口内;
- 如果窗口中没有该元素,则将该元素加入窗口,同时更新窗口长度最大值,tail 指针继续右移;
- 如果窗口中存在该元素,则将 head 指针右移,直到窗口中不包含该元素。
3.返回窗口长度的最大值。
def lengthOfLongestSubstring(self, s: str) -> int:
head=0
tail=0
if(len(s)<2):
return len(s)
res=1
while tail<len(s)-1:
tail+=1
if s[tail] not in s[head:tail]:
res=max(tail-head+1,res)
else:
while s[tail] in s[head:tail]:
head+=1
return res
方法二
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
res=[]
maxlen=0;
curlen=0;
for i in range(len(s)):
val=s[i]
if val not in res:
res.append(val)
curlen+=1
else:
index=res.index(val)
res=res[index+1:]
res.append(val)
curlen=len(res)
if(curlen>maxlen):
maxlen=curlen
return maxlen
二.最长不重复字符子串
def lengthOfLongestSubstring(s):
head = 0
tail = 0
if (len(s) < 2):
return len(s)
res=1
ans=[s[0]]
while tail < len(s) - 1:
tail += 1
if s[tail] not in s[head:tail]:
if res<len(s[head:tail+1]):
res=tail-head+1
ans.clear()
ans.append(s[head:tail+1])
else:
while s[tail] in s[head:tail]:
head += 1
return ans
s=input()
s=s[1:len(s)-1]
print(lengthOfLongestSubstring(s))