Longest Substring Without Repeating Characters

一、问题描述

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

意思是:给定一个字符串,要找出字符串中最大的连续子串,要求子串中的字符各不相同。


二、算法思想


给定任意一个字符串s

vector<char> v;//用于存放当前的子串

max=0;//记录最大的串数

for(i=0;i<s.size();i++)

{

it=find(v.begin(),v.end(),s[i]);

if(it!=v.end())//找到了

1)如果v.size()>max   max=v.size()

 2) 删除vector中从开始到it的所有元素 

3)再将当前的s[i]放入到vector中

else

将s[i]放入到vector中

}

时间复杂度:O(n^2)


三、代码实现


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int lengthOfLongestSubstring(string s)
    {
        int len=s.size();
        int i=0;
        int max=0;
        vector<char> v;
        vector<char>::iterator it=v.end();
        if(len<1)
            return 0;
        else if(len==1)
            return 1;
        v.push_back(s[i]);
        i++;
        while(i<len)
        {
            it=find(v.begin(),v.end(),s[i]);
            if(it==v.end())
            {
                v.push_back(s[i]);
            }
            else
            {
                if(v.size()>max)
                    max=v.size();
                v.erase(v.begin(),it+1);
                v.push_back(s[i]);
            }
            i++;
        }
        if(v.size()>max)
            max=v.size();
         

        return max;
    }


int main()

{
	cout<<lengthOfLongestSubstring("abac")<<endl;
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值