Longest Substring Without Repeating Characters

来源:互联网 发布:网络教育试点工作 编辑:程序博客网 时间:2024/06/10 16:27

一、问题描述

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