"Leetcode" longest Substring without repeating characters

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.