题目链接: https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/submissions/.
这道题基本思路是Sliding Window,例如input = “abcabcbb”。
tmp的状态如下:
“a”
“ab”
“abc”
当s[i]已经出现在了tmp中,我们可知以s[0]为开头的无重复字符的子串已达到最大长度。
所以我们记录其长度并滑动窗口。
“bca”
“cab”
“abc”
“cb”
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
tmp = "" #此处tmp作为滑动窗口
for i in range(len(s)):
if s[i] not in tmp:
tmp += s[i]
else:
result = max(result, len(tmp))
while tmp[0] != s[i]:
tmp = tmp[1:]
tmp = tmp[1:] + s[i]
result = max(result, len(tmp))
return result