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.
Run the worst time complexity O (n^2), Last[s.charat (i)] record I position of the word Fu Xiangmai to find the first occurrence of the position, the pre is equivalent to looking forward to the "wall", each time to find the same character to the new "wall" position, the pre is as far as possible back.
Public Static intlengthoflongestsubstring (String s) {Final intn=255; int[] last=New int[N];//record the last occurrence of a letter in the nearest position intAnslength=0; for(intI=0;i<s.length (); i++) {Last[s.charat (i)]=-1; } intPre=-1;//every word Fu Xiangmai find for(intI=0;i<s.length (); i++){ for(intj=i-1;j>pre;j--){ if(S.charat (j) = =S.charat (i)) {Last[s.charat (i)]=J; Break; } } if(Last[s.charat (i)]<i&&last[s.charat (i)]>pre) {Pre=Last[s.charat (i)]; } anslength=math.max (anslength,i-pre); } returnanslength; }
View java Code
http://blog.csdn.net/feliciafay/article/details/16895637 code with Run time O (n) complexity
intlengthoflongestsubstring (string s) {intn =s.length (); inti = 0, j = 0; intMaxLen = 0; BOOL exist[256] = {false }; while(J <N) {if(Exist[s[j]]) {MaxLen= Max (MaxLen, J-i); while(S[i]! =S[j]) {Exist[s[i]]=false; I++; } I++; J++; } Else{Exist[s[j]]=true; J++; }} maxlen= Max (MaxLen, ni); returnMaxLen;}
View Code
The outer while is changing the value of J, J changes from 0 to N (n is the length of the string), the inner while changes the value of I, the same, I change from 0 to N (the length of the string n). So add up, the time complexity is O (2*n), that is O (N).
It is also possible to think that the inner loop does not have to be done, only when J encounters a repeating character and needs to update the value of I, the memory loop is made, and I go through the number of steps up to n (the length of the string n).
This code also has a very interesting point, is not to forget in the loop body, but also write, maxlen = max (MaxLen, n-i). What is this for? Because when the last check is possible, J knows that there are no duplicate characters at the end of the string. The longest non-repeating substring found in the while loop body is only repeated when J encounters the repeating word characters.
LeetCode3 longest Substring without repeating characters