Leetcode每日一题:3.无重复字符的最长子串

在这里插入图片描述
在这里插入图片描述

双指针法

//双指针法
int lengthOfLongestSubstring(string s)
{
    int flag[130] = {0}; //标记数组
    int countMax = 0;    //记录长度
    int len = s.size();

    for (int i = 0, j = 0; j < len; j++) //i代表左指针,j代表右指针
    {
        flag[s[j]]++;          //标记该字符已出现过
        while (flag[s[j]] > 1) //说明该字符在前面已出现过,需移动左指针
        {
            flag[s[i++]]--; //保证左指针一定指向的没重复字符的子串的开头
        }
        countMax = j - i + 1 > countMax ? j - i + 1 : countMax;
    }
    return countMax;
}

暴力法
在这里插入图片描述

int lengthOfLongestSubstring(string s)
{
    int flag[130] = {0}; //标记数组
    int cur = 1;
    int count = 0, countRes = 0; //记录长度
    int len = s.size();
    int i = 0;

    for (; i < len; i++)
    {
        if (flag[s[i]] == cur) //说明存在重复字符
        {
            cur++;
            if (count > countRes) //记录该子串
            {
                countRes = count;
            }
            i=i-count+1;
            count = 0;
        }
        count++;
        flag[s[i]] = cur; //记录该字符
    }
    if (i == len && count > countRes)
        countRes = count;
    return countRes;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值