"Leetcode" 003 longest Substring without repeating characters

Source: Internet
Author: User

Title: Leetcode 003 Longest Substring without repeating characters

Test instructions: Gives a string that finds the oldest string with no repeating characters.

Example: "BBBBB" returns the length of "B" 1; "ABCABCBB" returns the length of "ABC" 3.

Ideas:

Dynamic planning. Dp[i] represents the longest length of a substring with no repeating character ending with an I-character, which requires a secondary array of idx[s[i]] to record the position of the last occurrence of the character's current character s[i], or 1 if it has not occurred. So get the following recursive formula:

In addition, because the range of the string length is not determined, it is implemented using a scrolling array. Dp[i&1] derived from dp[(i-1) &1].

The code is as follows:

1 classSolution {2  Public:3     intLengthoflongestsubstring (strings) {4         intLen =s.length ();5         if(len = =0)returnLen;6         intAns =1, idx[ -], dp[2];7memset (IDX,-1,sizeof(IDX));8dp[0] =1;9idx[s[0]] =0;Ten          for(inti =1; i < Len; i++) One         { A             if(Idx[s[i]] = =-1) -dp[i&1] = dp[(i-1) &1]+1; -             Else thedp[i&1] = min (I-idx[s[i]], dp[(i-1) &1]+1); -Idx[s[i]] =i; -ans = max (ans, dp[i&1]); -         } +         returnans; -     } +};

"Leetcode" 003 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.