题目描述:
Given a string, find the length of the longest substring
without repeating characters.
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", which the length is 3.
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
下面的python代码是根据right指向的字符是否出现在set中而反复的进行循环,代码如下:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
left, right = 0, 0
chars = set()
res = 0
while left < len(s) and right < len(s):
if s[right] in chars:
if s[left] in chars:
chars.remove(s[left])
left += 1
else:
chars.add(s[right])
right += 1
res = max(res, len(chars))
return res
参考资料:https://blog.youkuaiyun.com/fuxuemingzhu/article/details/82022530