给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<Character>();
int l = 0, r = 0;
int maxLength = 0;
while(l <= r && r < s.length()) {
if(!set.contains(s.charAt(r))) {
set.add(s.charAt(r));
r++;
maxLength = maxLength > r - l ? maxLength : r - l;
}
else {
set.remove(s.charAt(l));
l++;
}
}
return maxLength;
}
}
本题主要是滑动窗口以及set的使用
切忌想当然,左侧指针必须逐个滑动 否则set中的项可能会被错误删除