題目描述:
請從字符串中找出一個最長的不包含重複字符的子字符串,計算該最長子字符串的長度。
示例 1:
輸入: "abcabcbb"
輸出: 3
解釋: 因爲無重複字符的最長子串是 "abc",所以其長度爲 3。
示例 2:
輸入: "bbbbb"
輸出: 1
解釋: 因爲無重複字符的最長子串是 "b",所以其長度爲 1。
示例 3:
輸入: "pwwkew"
輸出: 3
解釋: 因爲無重複字符的最長子串是 "wke",所以其長度爲 3。
請注意,你的答案必須是 子串 的長度,"pwke" 是一個子序列,不是子串。
思路:雙指針法固定滑動窗口。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
# 雙指針法固定滑動窗口大小
if len(s)<2:return len(s)
head,tail=0,0
res=1 #窗口起始大小
while tail < len(s)-1:
tail +=1
if s[tail] not in s[head:tail]:
#注意:這裏tail-head是原始窗口大小,因爲s[tail]不在窗口裏面,所以窗口大小需要擴大一個,因此加1
res=max(tail-head+1,res)
else:
while s[tail] in s[head:tail]:
head+=1
return res