Given a string, find the length of the longest substring without repeating characters.
Example
Example 1:
Input: “abcabcbb” Output: 3 Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb” Output: 1 Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew” Output: 3 Explanation: The answer is “wke”, with the length of 3.
Solution
classSolution{ publicintlengthOfLongestSubstring(String s){ int cur=0; //Cursor int len=s.length(); //Length char str[]=newchar[len]; //Array int letters[]=newint[128]; //Counter int longest=0; //Longest int maxLetter=0; //Index of max int lettersIndex[]=newint[128]; //Index of character int former=0; //Former position if repeat int letter=0; //Ascii of letter for (;cur<len;cur++) str[cur]=s.charAt(cur); for (cur=0;cur<len;cur++) { for (int index=cur;index<len;index++) { letter=str[index]; //Letter --- str[index]-'A' lettersIndex[letter]+=index; //Sum of position, to find the former. if (++letters[letter]==2) { //Repeat! maxLetter =IntStream //Stream .range(0,letters.length) .reduce((i,j)-> //Lambda expression letters[i]>letters[j]?i:j) .getAsInt(); former=lettersIndex[letter]-index; longest=longest>index-cur?longest:index-cur; cur=former; //cur=former+1, cause 'c++' break; } if (index==len-1) { //No repeat longest=longest>len-cur?longest:len-cur; cur=len; //End break; } } zeros(letters); zeros(lettersIndex); } return longest; } publicint[] zeros(int[] array) {for (int i=0;i<array.length-1;i++) array[i]=0; return array;} }