首页 > 其他 > 详细

3.Longest Substring Without Repeating Characters(string; DP)

时间:2015-07-11 06:41:08      阅读:232      评论: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.

 

思路:使用动态规划,记住当前最长 substring及开始的字符位置,这样时间复杂度最坏O(n2),最好情况下O(n)

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s=="") return 0;
        
        //状态信息
        int maxLen = 1;
        int curLen = 1; 
        int startIdx = 0; 
        
        int i, j;
        for(i = 1; i < s.length(); i++){
            for(j = startIdx; j < i; j++){
                if(s[j] == s[i]){
                    //更新状态信息
                    if(curLen > maxLen) maxLen = curLen;
                    startIdx = j+1; 
                    curLen = i - startIdx + 1;
                    break;
                }
            }
            if(j == i){
                curLen++;//更新状态信息
            }
            
            if(curLen > maxLen) maxLen = curLen;//更新状态信息
        }
        return maxLen;
    }
};

 

3.Longest Substring Without Repeating Characters(string; DP)

原文:http://www.cnblogs.com/qionglouyuyu/p/4637973.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!