3. Longest Substring Without Repeating Characters

原题链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/
在给定的字符串中找出最长的连续不重复字符串的长度。

我的思路:
1.遍历字符串的substring,每次向后推移一位,当遍历的substr长度小于当前的max_str的时候遍历结束。
2.遍历字符串的时候建一个字典,检查当前的字母是否在字典中已经存在。如果不存在,在字典中添加key;如果存在,直接返回i。
感觉这道题应该可以用DP来做,运行时间可以更短···

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        max_str = 0
        for i in range(len(s)):
            char = s[i:]
            if len(char) > max_str:
                no_rep_char_len = self.no_repeat(char)
                if no_rep_char_len > max_str:
                    max_str = no_rep_char_len
        return max_str
            
    def no_repeat(self, s):     
        dict = {}
        for i in range(len(s)):
            if s[i] not in dict:
                dict[s[i]] = 1
                i += 1
            else:
                return i
        return i

答案里sliding window的解法:
如果一个字字符串s[i,j-1] 已经被检查过不含有重复的字母,那么其实我们只需要检查第j个字母s[j]是否在s[i, j-1]中即可。
如何检查呢?这里用hash set,检查一个字母是否在子字符串中只需要o(1)的时间。

class Solution:
    def lengthOfLongestSubstring(self, s):
        dct = {}
        max_so_far = curr_max = start = 0
        for index, i in enumerate(s):
            if i in dct and dct[i] >= start:
                max_so_far = max(max_so_far, curr_max)
                curr_max = index - dct[i]
                start = dct[i] + 1
            else:
                curr_max += 1
            dct[i] = index
        return max(max_so_far, curr_max)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值