首页 > 其他 > 详细

LeetCode OJ:Longest Substring Without Repeating Characters

时间:2014-02-01 14:55:00      阅读:388      评论:0      收藏:0      [点我收藏+]

Longest Substring Without Repeating Characters

 

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.


算法思想:

首先想到可以用动态规划,设dp[i]表示的是与i位置元素相同的上一个元素位置

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        const int len = s.length();  
        int *dp = new int[len+2];  
        int last[256];  
        for (int i = 0; i < 256; ++i) last[i] = len;  
        dp[len] = len;  
      
        for (int i = len - 1; i >= 0; --i)  
        {  
            dp[i] = min(dp[i+1], last[s[i]] - 1);  
            last[s[i]] = i;  
        }  
      
        int ans = -1;  
        for (int i = 0; i < len; ++i)  
        {  
            const int ret = dp[i] - i;  
            ans = max(ans,ret);  
        }  

        return ans + 1;
    }
};

有个更加精炼的版本

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int last[256];//保存字符上一次出现的位置
        memset(last, -1, sizeof(last));

        int idx = -1, ans = 0;//idx为当前子串的开始位置-1
        for (int i = 0; i < s.size(); i++)
        {
            if (last[s[i]] > idx)//如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1
            {
                idx = last[s[i]];
            }

            ans = max(ans,i-idx);

            last[s[i]] = i;
        }
        return ans;
    }
};


LeetCode OJ:Longest Substring Without Repeating Characters

原文:http://blog.csdn.net/starcuan/article/details/18890247

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