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

【LeetCode】Longest Substring Without Repeating Characters

时间:2014-12-23 15:05:53      阅读:174      评论: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.

 

动态规划。

访问到第end个元素时,假设s[begin,...,end]是以s[end]为结尾的最长无重复子串。

那么当访问到end+1个元素时,有两种情况:

(1)s[end+1]没有在之前出现过(用map记录char->index对),那么以end+1结尾的最长无重复子串必定是s[begin,...,end+1],并将s[end+1]加入map

(2)s[end+1]在之前出现过。

a. m[s[end+1]]取得的下标比begin还小,则不影响当前情况,以end+1结尾的最长无重复子串仍然是s[begin,...,end+1],并将s[end+1]加入map

b. m[s[end+1]]取得的下标比begin大,那么以end+1结尾的最长无重复子串变为s[m[s[end+1]]+1,...,end+1],,并将s[end+1]加入map

 

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char, int> m;
        int begin = 0;
        int ret = 0;
        for(int end = 0; end < s.size(); end ++)
        {
            if(m.find(s[end]) != m.end())
                begin = max(begin, m[s[end]]+1);
            m[s[end]] = end;
            ret = max(ret, end-begin+1);
        }
        return ret;
    }
};

技术分享

【LeetCode】Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/ganganloveu/p/4179935.html

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