【leetcode刷题】3. 无重复字符的最长子串(滑动窗口法)系列总结

3. 无重复字符的最长子串(Medium)

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        # 方法一:滑动窗口
        # 如果字符串s为空,返回0;为1,返回1。
        if s == "": return 0
        if len(s) == 1: return 1
        left = 0
        lookup = set()
        max_len, cur_len =0, 0
        for i in range(len(s)):
            cur_len += 1
            while s[i] in lookup:
                lookup.remove(s[left])
                left += 1
                cur_len -= 1
            max_len = max(max_len, cur_len)
            lookup.add(s[i])
        return max_len

        # 方法一:滑动窗口+切片(未理解)
        # length, j = 0, -1
        # for i,x in enumerate(s):
        #     if x in s[j+1:i]:
        #         length = max(length, i-j-1)
        #         j = s[j+1:i].index(x)+j+1
        # return max(length, len(s)-1-j)

        # 方法二:动态规划
        # if s == "": return 0
        # if len(s) == 1: return 1

        # def find_left(s, i):
        #     tmp_str = s[i]
        #     j = i - 1
        #     while j >= 0 and s[j] not in tmp_str:
        #         tmp_str += s[j]
        #         j -= 1
        #     return len(tmp_str)
        # length = 0
        # for i in range(0, len(s)):
        #     length = max(length, find_left(s, i))
        # return length

 

参考链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/hua-dong-chuang-kou-by-powcai/

你可能感兴趣的:(Leetcode刷题)