题目地址
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
总结
这是自己碰见的第一道滑动窗口题目
拿到题,我其实第一想法是暴力枚举,但是想了想时间复杂度太高。
滑动窗口,顾名思义,定义两个指针,来回进行滑动。
这里我画图举个栗子。
1,2作为移动步骤,先j为左边界,i向右滑动,滑到第二次a的时候,j向右再滑动。
代码
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] last = new int[128];
Arrays.fill(last, -1);
int start = 0;
int res = 0;
for (int i = 0; i < s.length(); i++) {
int index = s.charAt(i);
start = Math.max(start, last[index] + 1);
res = Math.max(res, i - start + 1);
last[index] = i;
}
return res;
}
}