题目:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
思路:维护两个指针,令其所指当前子字符串为没有重复字符。每次p2向后移动一位,如果p2所指字符不在当前子串中则判断是否是当前最长的没有重复的子串,如果p2所指字符已经存在则移动p1以使子串保持没有重复字符。
代码:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
cur_max = 1
p1 = 0
p2 = 1
while p1<len(s) and p2<len(s):
if s[p2] not in s[p1:p2]:
if p2-p1+1 > cur_max:
cur_max = p2-p1+1
else:
p1 = s.index(s[p2],p1)+1
p2 += 1
return cur_max