[LeetCode] #3 无重复字符的最长子串
给定一个字符串
s
,请你找出其中不含有重复字符的 最长子串 的长度。
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是
"abc",所以其
长度为 3。
使用HashSet维护滑动窗口
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<>();
int res = 0;
for(int start = 0, last = 0; last < s.length(); last++) {
while(set.contains(s.charAt(last))) set.remove(s.charAt(start++));
set.add(s.charAt(last));
res = Math.max(res, last - start + 1);
}
return res;
}
}
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] last = new int[128];
for(int i = 0; i < 128; i++) {
last[i] = -1;
}
int n = s.length();
int res = 0;
int start = 0;
for(int i = 0; i < n; 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;
}
}