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

一些想说的话

零零碎碎利用周末和晚上的时间总算把算法教程过完了一遍

白天研究了一会redis,想着晚上做做算法题练练手

打开LeetCode又是被一顿血虐

前路漫漫,还是需要更多的时间

但愿时间还够用吧

加油

问题描述

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

示例 1:

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

解决方案

暴力法:(直接超时,但是能用- - )

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = 0
        n = len(s)
        res = 0
        for i in range(n):
            for j in range(i+1,n+1):
                new_str = s[i:j]
                n_res = len(new_str)
                if n_res==len(set(new_str)):
                    if res<n_res:
                        res = n_res
                    
        return res

hashmap+滑动

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {}
        res, last_match = 0, -1
        for i, c in enumerate(s):
            if c in dic and last_match < dic[c]:
                last_match = dic[c]
            res = max(res, i - last_match)
            dic[c] = i
        return res

核心思路就是建立一个字典来保存出现过的字符串

遍历的过程中每次比对结果的最大值是必须的

  1. 如果当前的字符C在dict中,且最后匹配值last_match要小于上次c出现的位置
    • 则更新last_match为上次c出现的位置
  2. 更新最大值
  3. 把字符作为KEY,索引i作为value保存在dict中

猜你喜欢

转载自www.cnblogs.com/huang-yc/p/10328569.html