方法:滑动窗口
滑动窗口题型的基本模板:
for (int l = 0, r = 0; r < n; r++){
//外层移动右边界,里层的循环移动左边界
while(l <= r && check()){
//移动左边界
}
}
放到本题上就是:
移动右边界,判断当前是否含有该字符,并移动左边界到不包含该字符的位置,移动的同时删除中间已经不需要包括的字符
class Solution {
public int lengthOfLongestSubstring(String s) {
char[] ss = s.toCharArray();
Set<Character> set = new HashSet<>();
int res = 0;
for(int left = 0, right = 0; right < s.length(); right++){
char ch = ss[right];
while(set.contains(ch)){
set.remove(ss[left]);
left++;
}
set.add(ss[right]);
res = Math.max(res, right - left + 1);
}
return res;
}
}
我还用Map写了,和模板会有出入,时间复杂度还是O(N)
里层少了层循环
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character,Integer> map = new HashMap<>();
int length = s.length();
int ans = 0;
int tempAns = 0;
int l = 0,r =0;
while(r < length){
if(!map.containsKey(s.charAt(r)) || map.get(s.charAt(r)) < l){
tempAns++;
}else{
ans = Math.max(ans,tempAns);
l = map.get(s.charAt(r)) + 1;
tempAns = r - l + 1;
}
map.put(s.charAt(r),r);
r++;
}
ans = Math.max(ans,tempAns);
return ans;
}
}