leetcode oj-3

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、返回。

 注意:这道题为什么要往前比,而不是往后比?

 比如现在有字符串  “abcb” 从前往后的话需要比很多遍才能够判断是否有重复,a跟b,a跟c,a跟b,b跟c....

而从后往前比   则可以利用一个index,前面的最近相同的字符,b跟a比,c跟ab比都不同,则前面三个都不同,index=0,只要b跟这三个都不同就行了,假如有相同就记录下这个位置。

原文地址:https://www.cnblogs.com/maydow/p/4622415.html