3. Longest Substring Without Repeating Characters

本文介绍了一种寻找字符串中最长无重复字符子串的方法,提供了两种不同时间复杂度的实现方案,并详细解释了每种方法的工作原理。

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

3. Longest Substring Without Repeating Characters
Difficulty: Medium

Given a string, find the length of the longest substring without repeating characters.
Examples:
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.

给定一个字符串,找到不含相同字母的最长子字符串,返回该子字符串的长度。
如:给定”abcabcbb”—-“abc”—-len=3
给定”bbbbb”—-“b”—-len=1
给定”pwwkew”—-“wke”—-len=3

思路:用一个变量start标记当前子串的头,一个标记子串尾。不断往后扫描,当有字符前面出现过了,记录当前子串的长度和maxlen的比较结果。然后更新start标记。

方法一:时间复杂度=O(n^2),空间复杂度=O(1)

class Solution {
public:
    int lengthOfLongestSubstring(string s);
};

int Solution::lengthOfLongestSubstring(string s)
{
    if (s == "")
    {
        return 0;
    }

    int len = 1;
    int maxlen = 1;
    int start = 0;
    for (int i = 1; i<s.size(); i++)
    {
        int j;
        for (j = start; j<i; j++)
        {
            if (s[j] == s[i]) //当前字符重复了,更新start和len
            {
                start = j + 1;
                len = i - start + 1;
                break;
            }
        }
        if (j == i) //当前字符没有重复
        {
            len++;
            if (len>maxlen)
            {
                maxlen = len;
            }
        }
    }
    return maxlen;
}

方法二:时间复杂度=O(n)+O(n)=O(n),空间复杂度=O(256)

class Solution {
public:
    int lengthOfLongestSubstring(string s);
};

int Solution::lengthOfLongestSubstring(string s)
{
    bool *type=new bool[256];
    memset(type,false,256);

    int len=0;
    int maxlen=0;
    int start=0;
    for(int i=0;i<s.size();i++)
    {
        if(type[s[i]]==false)  //当前字符没有重复
        {
            len++;
            type[s[i]]=true;
        }
        else                   //当前字符与前面的字符重复
        {
            while(s[start]!=s[i])  //重新记录子字符串的start和长度
            {
                type[s[start]]=false;
                start++;
            }
            start++;
            len=i-start+1;
        }
        if(len>maxlen)
        {
            maxlen=len;
        }
    }
    delete [] type;
    return maxlen;
}

可以用hash表来代替type[256],查找当前字符是否已经出现过,在字符串较短时可以降低空间复杂度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值