Q:Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
这道题我另外加上了打印最长字符串的语句
1 public static int lengthOfLongestSubstring(String s) { 2 int startIndex=0,maxLength=0,newIndex=0,count=1;; 3 char[] cs=s.toCharArray(); 4 int l=cs.length; 5 if(l==1) 6 { 7 System.out.println(s); 8 return 1; 9 } 10 for(int i=1;i<l;i++) 11 { 12 for(int j=i-1;j>=newIndex;j--) 13 { 14 if(cs[i]==cs[j]) 15 { 16 newIndex=j+1; 17 break; 18 } 19 count++; 20 } 21 if(count>maxLength) 22 { 23 startIndex=newIndex; 24 maxLength=count; 25 } 26 count=1; 27 } 28 System.out.println(new String(Arrays.copyOfRange(cs, startIndex, startIndex+maxLength))); 29 return maxLength; 30 }
思路如下
1、将字符串转换成字符数组
2、假如字符串只有一个字符,就直接返回//这个不能忽略
3、从第二个字符开始往前判断是否有重复,直到上一次重复的那个index,
4、当发现重复,就记录下,作为下次循环的终点
5、当长度大于记录长度,就更新长度。
6、返回。
时间: 2024-10-21 14:56:58