#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
int lengthOfLongestSubstring(string s)
{
if (!s.size()) return 0;
const char* cp = s.c_str();// 将string 转换成一个 const char * 格式
/*std::map<char, int> mapStr; map is slower than vector 71% -> 99% */
vector<int> mapStr(256, 0);// 一维256长度的向量,初始化全部为0
int start = 1;
int end = 1;
int max = 0;
while (true)
{
char cha = *cp; //cp 是第一个字符的地址,*cp 是第一个字符
if (cha == '\0')
{
break; //读取到字符串结尾时退出
}
/*if get same char, wo need calculate the length, and store the best */
if (mapStr[cha] != 0)
{
/*wo do not need care the position if it samller than the start position
becase [ a, b, d, e, f, d, a] , the a -> a list is broken by d, and start position is 4(d + 1)*/
if (mapStr[cha] >= start)
{
int length = end - start;
if (max < length)
{
max = length;
}
start = mapStr[cha] + 1;
}
}
mapStr[cha] = end;
cp = cp + 1;
end += 1;
}
int c = end - start;
if (c > max)
{
max = c;
}
return max;
}
int main()
{
cout << "Hello World!\n";
string str;
cin >> str;
int a = lengthOfLongestSubstring(str);
cout << "这个字符串最大不重复的子字符个数为" << a << endl;
return 0;
}
算法分析(不同字符的子字符串最大长度)
最新推荐文章于 2021-08-22 18:05:12 发布