看了这题,其实我优点懵逼。。。没啥思路,也不知道第一次代码是参考了哪里写出来里的。。。但是看了code ganker的代码和解释后,豁然开朗,自己按照思路实现一遍就好。。。
第一次代码如下,用一个char[] 来记录是否已经出现过某个字母。。。
public class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLen=0;
int i=0;
int j=0;
int tag=0; // tag tells which loop did the program finally exit;
int[] checklist= new int[256]; // in the book, the variable name is charMap, which is also good
while(j<s.length()){ // error: s is a String, should use s.length()
Arrays.fill(checklist, -1); // set all elem to my default value -1, means not appeared before, the non-negative value means the position of character: s.charAt(j)
for(j=i; j<s.length(); j++){
if(checklist[s.charAt(j)]==-1){
checklist[s.charAt(j)]=j;
//System.out.println("checklist[s.charAt(j)]->"+(int)s.charAt(j)+"="+checklist[s.charAt(j)]);
tag=0; // tag tells which loop did the program finally exit; 0 means exiting here, the final char is NOT repeated
}else{
maxLen=Math.max(j-i, maxLen);
i=checklist[s.charAt(j)]+1;
tag=1; // tag tells which loop did the program finally exit; 1 means exiting here, the final char is repeated
j++;
break;
}
//System.out.println("tag:"+tag);
}
}
// when exit while(), j==s.length-1, need to consider the last substring, two case: last character is repeating char or not
if(tag==1) maxLen=Math.max(maxLen,j-1-i);
else if(tag==0) maxLen=Math.max(maxLen,j-1-i+1);
return maxLen;
}
}
今天写的代码:具体思路和解释见:http://blog.csdn.net/linhuanmars/article/details/19949159
public class Solution {
public int lengthOfLongestSubstring(String s) {
int max=0;
int left=0;
int right=0; // left and right are the side of valid window that scans over the substring
Set<Character> set= new HashSet<>();
while(right<s.length()){
char ch=s.charAt(right);
if(set.contains(ch)){
max=Math.max(max, right-left);
while(s.charAt(left)!=ch){ //如果但left==right,说明就是最后两个字母重复了
set.remove(s.charAt(left));
left++;
}// 以上就是把left扫过的字母都移除了,重复的那个字母其实是不用移除了,因为right已经指中,在下一次while中会用到。
left++; // !!!通过上面的while只是找到了repeat char,但是left还得右移一位
}
else{
set.add(ch);
}
right++;
}
return Math.max(max, right-left); // since the right will be s.length(), so do not need to +1 here
}
}