最大不重复子串的长度及其索引

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;

int max(int num1, int num2)
{
    return num1 >= num2 ? num1 : num2;
}


int lengthOfLongestSubstring(char* s) {
    int max_lengthp = 0;
    int book[256];
    for (int i = 0; i < 256; i++) book[i] = 0;
    int i = 0;
    int j = 0;
    int length = strlen(s);
    while (j < length)
    {
        if (book[(int)s[j]] == 1)
        {
            while (s[i] != s[j]) book[(int)s[i++]] = 0;
            i++;
        }
        book[(int)s[j]] = 1;
        j++;
        if (j - i > max_lengthp) max_lengthp = j - i;
    }
    max_lengthp = max_lengthp > (j - i) ? max_lengthp : (j - i);
    return max_lengthp;
}


int func(string A, int n)
{
    int m[256];
    memset(m, -1, 256 * sizeof(int));

    int pre = -1, res = 0; 
    int lastres = 0;
    int minindex = -1, maxindex = -1;
    //起始索引为-1,这里是初始的新子串的上个索引
    for (int i = 0; i < n; ++i)
    {
        pre = max(pre, m[A[i]]);//不断更新非重复子串的起始索引
        //当遇到出现过的字符,就更新起始索引为新子串的前一个索引
        //这样res=当前索引(i)-新子串起始索引的前一个索引(pre)
        res = max(res, i - pre);//不断更新非重复子串的最大长度
        if (res >= lastres) {
            cout <<"res:"<<res << endl;;
            maxindex = i; minindex = pre+1;
            lastres = res;
        }
        //当遇到出现过的字符时,res=当前出现的字符索引-上次出现相同字符的索引,即是非重复子串的长度

        m[A[i]] = i;//字符字典上,放上索引
    }
    cout <<"minindex:"<< minindex <<"maxindex:"<< maxindex << endl;

    return res;
}

int main(void)
{
    string str;
    cin >> str;
    cout << func(str, str.length()) << endl;
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值