首页 > 代码库 > 【LeetCode】Longest Substring Without Repeating Characters

【LeetCode】Longest Substring Without Repeating Characters

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