使用循环实现。其中创建了一个长度为26的辅助数组,存放各字符在字符串中最后出现的位置。
/**
*Copyright @ 2019 Zhang Peng. All Right Reserved.
*Filename:
*Author: Zhang Peng
*Date:
*Version:
*Description:剑指offer<第二版> 面试题48 最长不含重复字符的子字符串
**/
#include<iostream>
using namespace std;
int findLongStr(char * str)
{
int s = strlen(str);
if (s == 0)
return 0;
int record[26];
for (int i = 0; i < 26; i++)
record[i] = -1;
int start = 0;
record[str[0] - 'a'] = 0;
int maxlen = 1;
for (int i = 1; i < s; i++)
{
int findindex = str[i] - 'a';
int len = 0;
if (record[findindex] == -1)
len = i - start + 1;
else
{
if (record[findindex]<start)
len = i - start + 1;
else
{
len = i - record[findindex];
start = record[findindex]+1;
}
}
if (len>=maxlen)
{
cout << "length " << len << " str:" << endl;
maxlen = len;
for (int k = start; k < (start+maxlen); k++)
cout << str[k];
cout << endl;
}
record[findindex] = i; //记录最新的字符所处位置
}
return maxlen;
}
int main()
{
char * testcase = "arabcaacfr";
int num = findLongStr(testcase);
cout << "max num: " << num << endl;
system("pause");
return 0;
}
运行结果如下: