Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
解法1:
通过2重循环求,时间复杂度n平方,提交超时
//主要思路为:
当遇到和容器里的元素相同时,则终止内存循环,然后比较ibest,再从外层循环的下一位构建容器,再重复上面的操作
解法2:
int main()
{
string s;
while (cin >> s)
{
int ibest = 0;
int current = 0;
vector<char>cvec;
for (size_t i = 0; i < s.size(); i++)
{
auto flag = find(cvec.begin(), cvec.end(), s[i]);
if ( flag== cvec.end())
{
current++;
cvec.push_back(s[i]);
}
else
{
if (current > ibest)ibest = current; //每次中断要比较一次
cvec.erase(cvec.begin(), flag+1); //一般erase(begin,end) 删除的是[begin,end)的数据,故要将flag位置的数据删除,flag必须+1
current = cvec.size();
i = i - 1; //因为是从i此结束的,容器中还没i的元素,要添加进来,所以i回退一个
}
if (current > ibest)ibest = current; //这里再添加比较是考虑如果没有一次中断,则无法进入上的else进行比较,所以得不到ibest;
}
cout << ibest << endl;
}
}
分析:
当添加的元素与容器内的元素有相同时,则此时要比较current 与ibest ,然后修改容器,将容器中开始位置到flag的位置上的元素删除掉,为什么可以删除呢?因为,例如 fghkbcdacilj
当你从f开始搜,当遇到重复的c时,此时的长度为 8 ,而如果你再从f的下一个g开始搜,依然是遇到c时结束,此时长度为7,长度肯定比第一次小,所以直接可以将第一个c(包括c)前面的字符全部从容器中删除,然后接着搜,所以调整容器,