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" are "abc", which the length is 3. For "bbbbb" the longest substring are "B", with the length of 1.
Dynamic planning.
When accessing to the end of an element, assume that S[begin,..., end] is the longest, non-repeating substring ending with s[end].
There are two scenarios when accessing end+1 elements:
(1) s[end+1] did not appear before (with map record Char->index pair), then the longest non-repeating substring ending with end+1 must be S[begin,..., end+1], and add s[end+1] to map
(2) s[end+1] appeared before.
A. M[s[end+1]] The subscript obtained is smaller than begin, it does not affect the current situation, the longest non-repeating substring ending with end+1 is still s[begin,..., end+1], and adding s[end+1] to the map
B. m[s[end+1]] [] The index obtained is greater than begin, then the longest non-repeating substring ending with end+1 becomes s[m[s[end+1]]+1,..., end+1], and s[end+1] is added to the map
classSolution { Public: intLengthoflongestsubstring (strings) {map<Char,int>m; intBegin =0; intRET =0; for(intEnd =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); } returnret; }};
"Leetcode" longest Substring without repeating characters