码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】3. Longest Substring Without Repeating Characters

时间:2016-08-02 06:35:36      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

 

其实思路还是蛮简单的,首先必须是子串,子串必须连续,连续首先想到的就是字符串扫描,也就是循环。(试图用递归做,比较恶心)

扫描过程中就是收集substr的过程,如果没有重复的字符,就把该字符收进substr,然后和maxlen比较,maxlen记最大的substr长度。

如果出现重复字符,判断是否已经到原来字符串的尾巴,如果到了就返回maxlen,如果没到,就要更新substr,更新substr的过程中先不需要跟maxlen有什么变化。

 

注意点:

string自己的find函数好像不好用,返回下标,没找到返回std::npos。

string自己的substr函数原型是  substr(int start,int len);

 

最后用的是stl里的find:Template<T>::iterator find(iterator begin,iterator end,T need);

用的string的构造函数  string(iterator begin,iterator end);

 

 

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int len=s.length();
        if(len==0||len==1)
            return len;
        string substr="";
        int maxlen=0;
        for(int i=0;i<len;i++){
            if(find(substr.begin(),substr.end(),s[i])==substr.end()){
                substr+=s[i];
                if(substr.length()>maxlen)
                    maxlen=substr.length();}
                else{
                    auto j=find(substr.begin(),substr.end(),s[i]);
                    if(j==s.end()-1)
                        return maxlen;
                    if(j==substr.end()-1){
                        substr="";
                        substr+=s[i];}
                    else {
                        string tmp(j+1,substr.end());
                        tmp+=s[i];
                        substr=tmp;
                    }
                }
            }
        if(substr.length()>maxlen)
            maxlen=substr.length();
        return maxlen;
    }
};

 

【leetcode】3. Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/LUO77/p/5727882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!