LeetCode # Array # Easy # 3.Longest Substring Without Repeating Characters

题目:Given a string, find the length of the longest substring without repeating characters.

Idea: Use a table (array) to store the position of characters in the string. Because a character is essentially a unicode number, an array is created, the subscript of the array represents the ASCII code of the character, and the element represents its position in the string.

When a previously repeated character is encountered, the maximum substring length may be found; after the comparison, scanning starts from the digit after the first occurrence of the character. See below:

Code:

1       public  int lengthOfLongestSubstring(String s) {
 2          int length = s.length();         
 3           if (length<=1 ){
 4               return length;
 5           }
 6           int start=0 ;
 7           int end = 0 ;
 8           int max = 1; // Maximum non-repeating substring length 
9           int [] countTable = new  int [256]; // The table is used to store the position where (the character at the end position) appears in the string. 
10           Arrays.fill(countTable, -1 );
 11           while(end < length){
 12              char c = s.charAt(end);
 13               if (countTable[c] >= start ){ // If the corresponding occurrence of this character is not less than start (indicating that the character is repeated), Then set start to the position after this position. 
14                   start = countTable[c]+ 1 ;
 15               }
 16               max = Math.max(max, end-start +1); // update max value; 
17               countTable[c]= end; // update countTable, 
18               end++ ;             
 19           }
 20           return max;
 21      }

refer to:

https://blog.csdn.net/likecool21/article/details/10858799 The initial value of the code end in the original link is set to 1, which will cause problems.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324930003&siteId=291194637
Recommended