1、通过设置左右指针,常规思维易于理解
2、通过滑窗的方法解决该问题,也进一步体验到了while的妙处
举例说明while的用法:
a = [2,1,3]
b = 0
while 1 in a:
a.pop(0)
b+=1
print(a)
print(b)
结果
[3]
2
正式解题代码(将list=[]换成dict1=set()运行的更快)
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
l = 0
res = 0
list1 = []
for r in range(len(s)):
while s[r] in list1:
list1.pop(0)
l += 1
list1.append(s[r])
res = max(res, r-l+1)
return res
s = "abcbc"
ll = Solution().lengthOfLongestSubstring(s)
print(ll)
结果
3