#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;
}
最大不重复子串的长度及其索引
猜你喜欢
转载自blog.csdn.net/xiziyunqi/article/details/82622059
今日推荐
周排行