public class Solution {
public int lengthOfLongestSubstring(String s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int length = s.length();
int begin=0,end=0,maxLength=0,temp=0;//begin和end是所求substring的头尾位置
/*
* 计算机中ASCII码所能表示的字符个数是256
* 该数组的下标是每个字符对应的ASCII码
*/
boolean[] isExist = new boolean[256];//是否存在该字符的boolean数组
int[] position = new int[256];//字符的位置
for(int i = 0;i<length;i++){
char c = s.charAt(i);
end = i;
if(isExist[c]){
/*
* 如果存在该字符,则计算maxLength,并且截去该字符上一次出现位置之前的字符(boolean置为false)
* 重新确定begin
*/
temp = maxLength;//存储上一次的maxLength
maxLength = end - begin;
if(maxLength<temp){
maxLength = temp;
}
for(int j = begin;j<position[c]+1;j++){
char d = s.charAt(j);
isExist[d] = false;
}
begin = position[c]+1;
}
isExist[c]=true;
position[c]=i;
/*
*如果是最后一个字符,则直接计算出maxLength
*/
if(end == length-1){
temp = maxLength;
maxLength = end-begin+1;
if(maxLength<temp){
maxLength = temp;
}
}
}
return maxLength;
}
}
求最长无重复字符的substring的长度
最新推荐文章于 2022-04-01 14:46:23 发布
