My Leetcode journey, this chapter mainly completes the use of Java implementation algorithm. This is the third article longest Substring without repeating characters
All code Download: GitHub Link: GitHub link, click Surprise, write article is not easy, welcome everyone to take my article, and give useful comments, of course you can also pay attention to my GitHub;
1. Topic Description:
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.
2. My train of thought:
1. Use a character array to record whether characters are duplicated
2. Define the starting point of the No substring as J, the end point is defined as I
3.i increments when the character is already present in the character array, determine if Max is greater than i-j, and start with J to find out which character is the same, and the beginning J + + in the character array to remove the discarded characters;
4. If the last character in the string is not a repeating character, the outside of the loop determines whether to update Max
3. My AC Code
Packagecom.rlovep.string;/** * Longest Substring without repeating characters * my idea: * 1. Use a character array to record whether the character repeats * 2. Defines the starting point of no substring as J, and the endpoint is defined as I * 3.i increments When the character is already present in the character array, determine if Max is greater than I-j, find out which character is the same from J, and remove the lost character from the start of J + + in the character array; * 4. If the last character in the string is not a repeating character, the outside of the loop determines whether to update Max * @ Author Peace * * * * Public class longsubnrep { Public int lengthoflongestsubstring(String s) {if(s==NULL|| S.length () <=0)return 0;Char[] A=New Char[ the];intj=0;intmax=0;intI=0;Booleanflag=false; for(; I<s.length (); i++) {CharC=s.charat (i);if(a[c]==1){if(max< (I-J)) max=i-j; flag=false; for(intk=j;k<i;k++) {CharDup=s.charat (k);if(C==dup) {j=k+1; Break; }Else{a[dup]=0; } } }Else{a[c]=1; flag=true; } }if(flag==true&&max< (I-J)) max=i-j;returnMax } Public Static void Main(string[] args) {Char[] A=New Char[ the]; }}
Ok this chapter is introduced here from the Wpeace (blog.wpeace.cn)
Leetcode03-longest Substring without repeating characters Java version