3. 無重複字符的最長子串
public class LengthOfLongestSubstring3 {
public static void main(String[] args) {
String s = "abcabcbb";
System.out.println(lengthOfLongestSubstring(s));
}
private static int lengthOfLongestSubstring(String s) {
// 定義左右兩個指針
int left = 0, right = -1;
// 字符標記
int[] freq = new int[256];
// 長度
int length = 0;
while (left < s.length()) {
if (right + 1 < s.length() && freq[s.charAt(right + 1)] == 0) {
freq[s.charAt(++right)]++;
} else {
freq[s.charAt(left++)]--;
}
length = Math.max(length, right - left + 1);
}
return length;
}
}