题目:
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
题目大意:
找出字符串中最长没有相同字母的子字符串
题解:
这道题可以利用ASCII码,即每一个char类型的变量其实都是一个[0,255]的整数.用boolen类型的数组判断一个char是否在子串中.
public static int lengthOfLongestSubstring(String s) {
boolean[] flag = new boolean[256];
char[] charList = s.toCharArray();
int start = 0;
int max = 0;
int i = 0;
char ch;
while(i < charList.length){
ch = charList[i];
if(flag[ch]){
//如果char在子串中,则判断是原来的max大,还是i-start大.
max = Math.max(max,i-start);
//将char之前的字符都移出子串,修改子川开始的位置
for(int k = start;k<i;k++){
if(charList[k]==ch){
start = k+1;
break;
}
flag[charList[k]] = false;
}
}else{
//如果char不在子串中,则boolen[char] = true,表示char在子串中,
flag[ch] = true;
}
i++;
}
max = Math.max(max,i-start);
return max;
}