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.
分析:
此题应用two pointers的方法。 1. abcdbef 注意如果遇到相同的字母,具体来说,此时p1-> "a", p2 ->"d" ,那么下一步p2+1,则p2 ->"b",所以遇到相同的字母了,那么p1应该调到p1 ->"c".(b之后的位置)。
此外,还应该熟悉函数,Python函数find(value) == 找到对应的值在string中的index
另外,max_l计算的方法,还有method 2,不过道理都是一样的,只是计算max的时机不一样。
Python 代码:
<pre name="code" class="python">class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
if s == None:
return 0
p1 = 0
p2 = 0
l = len(s)
max_l = 0
while l > p2 :
if s[p2] not in s[p1:p2]:
max_l = max(max_l, p2 - p1 +1)
p2 = p2 + 1
else:
# method 2 -- max_l = max(max_l, p2 - p1)
p1 = p1 + s[p1:p2].find(s[p2]) + 1
p2 = p2 + 1
# method 2 -- max_l = max(max_l, p2 - p1)
return max_l