classSolution { publicintlengthOfLongestSubstring(String s) { HashSet<Character> set = newHashSet<Character>(); int n=s.length(); int len=0; for(int left=0,right=0;right<n;right++){ charc= s.charAt(right); while(left<right&&set.contains(c)){ //存在相同元素 set.remove(s.charAt(left)); left++; } set.add(c); len=Math.max(len,right-left+1); } return len; } }
知识点
滑动窗口模板:
1 2 3 4 5 6 7 8
//外层循环扩展右边界,内层循环扩展左边界 for (intl=0, r = 0 ; r < n ; r++) { //当前考虑的元素 while (l <= r && check()) {//区间[left,right]不符合题意 //扩展左边界 } //区间[left,right]符合题意,统计相关信息 }