Leetcode刷题记录19——无重复字符的最长子串

题源:https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/?envType=study-plan-v2&envId=top-100-liked

题目描述:
Leetcode刷题记录19——无重复字符的最长子串_第1张图片
思路一:
通过两个指针,第一个指针指向字串的开头,第二个指针向后找,直到找到重复的字符或者到达字符的末尾,第二个指针每向后移动一位,当前的子串长度加一,然后与最大长度作比较,留下更大的那个作为最长子串长度。
代码如下:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        max_len = 0     # 最长子串长度
        cur_max_len = 0 # 当前找到的最长子串长度
        cur_set = set()

        for i in range(len(s)):
            j = i
            cur_max_len = 0
            cur_set = set()
            while j < len(s) and s[j] not in cur_set:
                cur_set.add(s[j])
                j += 1
                cur_max_len += 1
                max_len = max(max_len, cur_max_len)
        
        return max_len

执行时间如下:
Leetcode刷题记录19——无重复字符的最长子串_第2张图片

你可能感兴趣的:(Leetcode刷题记录,leetcode,算法,职场和发展)