longest-substring-without-repeating-characters.py

longest-substring-without-repeating-characters.py

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

https://leetcode.cn/problems/longest-substring-without-repeating-characters/

结果: ⋆ ⋆ ⋆ \star\star\star

20220612
> https://leetcode.cn/problems/longest-substring-without-repeating-characters/

执行用时:60 ms, 在所有 Python3 提交中击败了84.22%的用户
内存消耗:15 MB, 在所有 Python3 提交中击败了96.26%的用户

time cost: 10 min

代码:

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        max_l = 0
        sub_s = ''
        for str in s:
            idx = sub_s.find(str)
            if idx != -1:
                sub_s = sub_s.split(str)[1]
            sub_s += str
            temp_l = len(sub_s)
            if temp_l > max_l:
                max_l = temp_l
            # print(sub_s)
        return max_l

思路

遍历序列 s s s的每个字符 s t r str str

初始化子序列 s u b _ s sub\_s sub_s,如果在 s u b _ s sub\_s sub_s中能找到 s t r str str,则说明该阶段的子序列查找完毕

s t r str str为标志分割 s u b _ s sub\_s sub_s,取后面的取代 s u b _ s sub\_s sub_s

key: 这里截取后的 s u b _ s sub\_s sub_s要加上 s t r str str,不然会漏掉这个字符

遍历完 s s s结束程序

你可能感兴趣的:(LeeCode,py,leetcode,动态规划,算法)