Given a string, find the length of the longestsubstring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that theanswer must be a substring, "pwke" is a subsequence andnot a substring.
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null){//判断字符串的合法性
return 0;
}
int result = 0;//保存子字符串长度
int start = 0;//字符起始位置
boolean[] flag = new boolean[256];
char[] arr = s.toCharArray();
for(int i = 0; i < arr.length; i++){
char current = arr[i];
if(flag[current]){//当前的字符已经访问过了,记录子串的长度。然后,重定向start
result = Math.max(result, i - start);
//重定向字符
for(int k = start; k < i; k++){
if(arr[k] == current){//判断相邻字符是否一样
start = k + 1;
break;
}
flag[arr[k]] = false;//将之前访问过的字符的标志重新设为false
}
}else{
flag[current] = true;
}
}
result = Math.max(arr.length - start, result);
return result;
}
}