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.
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s==null || s.isEmpty()==true) //判断是否为空
return 0;
int len = s.length();
int res = 1; //长度变量
int start = 0, cur = 1; //起始位,游标
int position[] = new int[256]; //利用字符的ASCII码值与数组的下标一一对应
Arrays.fill(position, -1); //将数组值全部设为-1
position[s.charAt(0)] = 0; //从第一位开始遍历,遍历后的字符对应数组中下标的值设为0
// loop and find corresponding result
while(cur < len){ //遍历
// s[cur] has not occurred
if(position[s.charAt(cur)] < start){ //当前遍历的字符之前没有遍历过,长度res加一,当前字符设为已遍历,数组值为0
res = Math.max(cur-start+1, res);
position[s.charAt(cur)] = cur;
}
// s[cur] has occurred in previous substring
else{
start = position[s.charAt(cur)] + 1; //当前字符已经遍历过,起始位加一
res = Math.max(res, cur-start+1);
position[s.charAt(cur)] = cur;
}
cur++;
}// End while loop
return res;
}
}