给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc" ,所以其长度为 3 。
代码
java
class Solution {
public int lengthOfLongestSubstring(String s) {
// 判空
if(s == null || s.length() == 0){
return 0;
}
// set用来存不重复的字符
HashSet<Character> set = new HashSet<>();
// 遍历s
// i用来控制遍历
int i = 0;
// l指向不重复的字符串最左边
int l = 0;
int max = Integer.MIN_VALUE;
while(i < s.length()){
if(!set.contains(s.charAt(i))){
set.add(s.charAt(i));
max = Math.max(max, i - l + 1);
i++;
}else{
// 当这个字符重复了,则将l位置上的字符删掉,l++,重新遍历判断
set.remove(s.charAt(l));
l++;
max = Math.max(max, i - l + 1);
}
}
return max;
}
}
思路(欢迎纠正)
使用滑动窗口的方法,通过双指针 i 和 l 来实现。 i 用于遍历字符串, l 始终指向不重复字符串的最左边。当遇到重复字符时,将 l 指向的字符从集合中删除,并将 l 向右移动一位,然后继续遍历判断,在此过程中不断更新最长无重复字符子串的长度 max .