The original question is as follows:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer "abc"
is, which the length is 3.
Given "bbbbb"
, the answer "b"
is, with the length of 1.
Given "pwwkew"
, the answer "wke"
is, with the length of 3. Note that the answer must was a substring, is "pwke"
a subsequence and not a substring.
Using dynamic programming, calculate the longest non-repeating substring at the end of the last character in the first n characters, and finally calculate the maximum value, the time complexity is O (n*n+n) =o (n^2). The code is as follows:
1 Public intlengthoflongestsubstring (String s) {2 if(s.length () = = 0){3 return0;4 }5 int[] A =New int[S.length ()];6A[0] = 1;7 intmax = 1;8 for(inti = 1; i< s.length (); i++){9 if(S.charat (i) = = S.charat (i-1)){TenA[i] = 1; One}Else{ A intj = 1; - for(; J < A[i-1]+1; J + +){ - if(S.charat (i) = = S.charat (i-j)) { the Break; - } - } -A[i] =J; + } - if(Max <A[i]) { +Max =A[i]; A } at } - returnMax; -}
Reference Source: https://github.com/pkufork/Martians/blob/master/src/main/java/com/pkufork/martians/leetcode/ Longestsubstringwithoutrepeatingcharacters3.java
Leetcode 3-longest Substring without repeating characters