LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串) --medium

本文介绍了一种使用动态规划方法解决寻找字符串中最长无重复字符子串的问题,提供了C++和Python两种语言的实现方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Given a string, find the length of the longest substring without repeating characters.

Example:
Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. 

Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

问题解析:

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

链接:

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

思路标签:

算法:DP

数据结构:Vector

解答:

1. C++
  • 假设L[i] = s[start … i],表示最长的子字符串,其中没有重复的元素,我们以Vector作为hashmap保存< 字符,索引>;
  • 然后访问s[i + 1]:
    • 1)如果s[i + 1]没有出现在散列表dict中,我们可以将s[i + 1]添加到散列表中,则有L[i + 1] = s[start … i + 1];
    • 2)如果s[i + 1]存在于dict中,并且dict中对应的索引是k;则令start = max(start,k),则L[i + 1] = s[start … i + 1],记录此时的最大长度;
  • 整个问题就是围绕不加入重复元素而展开的。
  • 时间复杂度:O(n)
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);
        int maxLen = 0, start = -1;
        for (int i = 0; i != s.length(); ++i) {
            if (dict[s[i]] > start)
                start = dict[s[i]];
            dict[s[i]] = i;
            maxLen = max(maxLen, i - start);
        }
        return maxLen;
    }
};
2. python
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = maxLength = 0
        usedChar = {}

        for i in range(len(s)):
            if s[i] in usedChar and start <= usedChar[s[i]]:
                start = usedChar[s[i]] + 1
            else:
                maxLength = max(maxLength, i - start + 1)

            usedChar[s[i]] = i

        return maxLength

算法相关

动态规划:https://www.zhihu.com/question/23995189

C++相关:

max方法依赖:#include <algorithm>

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值