
思路:滑动窗口。
复杂度分析:
1.时间复杂度:O(n)。
2.空间复杂度:O(1)。
(一)方法一:整型数组
java
class Solution {
public int lengthOfLongestSubstring(String s) {
char[] chars = s.toCharArray();
int n = chars.length;
int res = 0;
int left = 0;
int[] cnt = new int[128]; //ASCII码的字符集有128个字符
for(int right = 0;right < n;right++){
char c = chars[right];
cnt[c]++;
while(cnt[c] > 1){ //窗口内有重复元素
cnt[chars[left]]--; //移除窗口左端点字母
left++; //缩小窗口
}
res = Math.max(res,right - left + 1); //更新窗口长度的最大值
}
return res;
}
}
(二)方法二:布尔数组
java
class Solution {
public int lengthOfLongestSubstring(String s) {
char[] chars = s.toCharArray();
int n = chars.length;
int res = 0;
int left = 0;
boolean[] has = new boolean[128]; //ASCII码的字符集有128个字符
for(int right = 0;right < n;right++){
char c = chars[right];
// 如果窗口已经包含c,那么再加入一个c会导致窗口内有重复元素
// 所以要在加入c之前,先移出窗口内的c
while(has[c]){ //窗口内有c
has[chars[left]] = false;
left++; //缩小窗口
}
has[c] = true; //加入c
res = Math.max(res,right - left + 1); //更新窗口长度的最大值
}
return res;
}
}