首页 > 其他 > 详细

[LeetCode] Longest Substring Without Repeating Characters

时间:2014-04-02 08:30:35      阅读:488      评论: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.

Solution:

bubuko.com,布布扣
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int length = s.length();
        if(length < 2) return length;
        int *dp = new int[length];        
        int maxLen = 1;
        dp[0] = 1;
        for(int i = 1;i < length;i++)
        {
            int curLen = 0;
            bool noRepeat = true;
            for(int j = i - 1;j >= i - dp[i - 1];j--)
            {
                if(s[j] == s[i])
                {
                    curLen = i - j - 1;
                    noRepeat = false;
                    break;
                }
            }
            if(noRepeat) 
                dp[i] = dp[i - 1] + 1;
            else 
                dp[i] = curLen + 1;
            maxLen = max(maxLen, dp[i]);
        }
        //cout << maxLen << endl;
        return maxLen;
    }
};
bubuko.com,布布扣

[LeetCode] Longest Substring Without Repeating Characters,布布扣,bubuko.com

[LeetCode] Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/changchengxiao/p/3639289.html

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