leetcode-146- 最长不重复子串
longest-substring-without-repeating-characters
http://www.nowcoder.com/questionTerminal/5947ddcc17cb4f09909efa7342780048
最长不重复子串
双指针,用一个hash保存子串已经存在的字符,这里使用一个int数组,如果字符存在,那么hash[char]=1;
举个例子:abcbd,q指针一直向前走,当走到第二个b的时候,令p向前走,一直走到第一个p,q每次都令hash为1,p每次令hash为0;
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return int整型
*/
public int lengthOfLongestSubstring (String s) {
if(s==null || s.length()<=0){return 0;}
if(s.length()==1){return 1;}
int p=0,q=0,len=0,res=0;
// 判断字符是否存在的hash表
int[] hash=new int[128];
while(q<s.length()){
if(hash[s.charAt(q)]==0){
hash[s.charAt(q)]=1;
len++;
}else{
while(s.charAt(p)!=s.charAt(q)){
hash[s.charAt(p)]=0;
len--;
p++;
}
// 这个时候,p,q指向同一个字符,令p向前一步,但是len不减,因为q指向被算入了len
p++;
}
res=Math.max(res,len);
q++;
}
return res;
}
} 
查看12道真题和解析