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

Longest Substring Without Repeating Characters

时间:2015-04-19 15:49:13      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路:一遍遍历一边记录最大长度。如果出现重复字符,则从当前不重复的cursub string中截取重复位置之后的substr,并与重复字母拼接成新的cursub,判断新的cursub长度是否超过当前所知的最长。

复杂度分析:O(n) ,我的解法38ms,但leetcode有更快!待我研究下

开心的是又一次 bug free!

 

总结:3种解法:(1)string (2)two pointer (3)hashtable!  哇这么多方法。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        //check validation
        if(s.empty()) return 0;
        //check specail case or bound;
        int len=s.length();
        if(len==1) return 1;
        
        //general case
        string cursub;
        cursub=s[0];
        int lmax=1;
        int lcur=1;
        for(int i=1;i<len;i++){
            int pos=cursub.find(s[i]);
            if(pos>=0){
                if(pos+1==lcur) cursub.clear();
                else
                    cursub = cursub.substr(pos+1,cursub.length()-pos);
            }
            cursub+=s[i];
            lcur=cursub.length();
            if(lcur>lmax) lmax=lcur;
        }
        return lmax;
    }
};

 

Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/renrenbinbin/p/4439103.html

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