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