栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

leetcode最长回文子串_LeetCode[5]-最长回文子串?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode最长回文子串_LeetCode[5]-最长回文子串?

链接

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

题目描述

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

思路

使用递推的方法,充分利用之前的结论,避免重复计算,可以在最大程度上降低时间复杂度。

具体地,我们先以第一个位置为起点,向后查找最长的符合要求的子串[0…i]。那么接下来如何由这一结论推出以第二个位置为起点的最大子串长度呢?我们注意到,前一步遍历其实已经保证了[0…i]中不存在重复元素。我们如果把起点向右移动一个单位,其实相当于少了一个元素,因此再向后查找的时候允许与该元素重复了,相当于放开了一些限制。

代码 Python
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        occ = set()
        curr = 0
        r = 0
        for l in range(len(s)):
            while r < len(s) and s[r] not in occ:
                occ.add(s[r])
                r += 1
            curr = max(curr, r - l)
            occ.remove(s[l])
        return curr
C++
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
		int mark[128], len=s.length(), max=0, r=0;
		for(int i=0; i<128; i++) {
			mark[i]=0;
		}
		for(int l=0; l0) {
				mark[int(s[l-1])]--;
			}
			while(rmax?(r-l):max;
		}
		return max;
    }
    
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/783722.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号