3. Longest Substring Without Repeating Characters -- SlidingWindow

穿精又带淫゛_ 提交于 2020-01-15 01:40:00

 

3. Longest Substring Without Repeating Characters

 

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

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.

 

双指针,滑动窗口

 

 

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        if not s:
            return 0
        else:
            res = 1
        
        # two pointers
        left = 0
        right = 1
        
        for i in range(len(s)-1):
            if s[right] not in s[left:right]:
                res = max([right-left+1, res])
                right = right + 1
                
            else:
                left = left + 1
                while s[right] in s[left:right]:
                    left = left + 1
                right = right + 1
                    
        return res

 

 

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!