题目:Given a string, find the length of the longest substring without repeating characters.
思路:用一个表(数组)来存储字符在字符串中的位置。因为字符本质上是一个unicode数字,因此建立一个数组,数组的下标表示这个字符的ASCII码,元素表示其在字符串中的位置。
当遇到之前重复的字符,则可能找到了最大子串长度;进行比较后,从该字符首次出现的后一位开始扫描。见下图:
代码:
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;//最大非重复子串长度 9 int[] countTable = new int[256];//表用来存储 (end位置的字符)在字符串中出现的位置。 10 Arrays.fill(countTable, -1); 11 while(end < length){ 12 char c =s.charAt(end); 13 if(countTable[c] >= start ){//如果这个字符对应的出现位置不小于start(说明该字符是重复的),则将start设为该位置后一个位置。 14 start = countTable[c]+ 1; 15 } 16 max = Math.max(max, end-start +1);//更新max的值; 17 countTable[c]= end;//更新 countTable表, 18 end++; 19 } 20 return max; 21 }
参考:
https://blog.csdn.net/likecool21/article/details/10858799 原链接中代码end初始值设置为1,会有问题。