3. Longest Substring Without Repeating Characters

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)前面的字符全部从容器中删除,然后接着搜,所以调整容器,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值