给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
案例:
public int lengthOfLongestSubstring(String s) {
//Set用来判断是否遇到相同的字符
Set<Character> set = new HashSet<>();
int left = 0, right = 0, max = 0;
while (right < s.length()) {
if (!set.contains(s.charAt(right))) {
//如果Set没有s.charAt(right)该字符,right指针直接右移
set.add(s.charAt(right));
right++;
} else {
//如果碰到Set集合内已有的字符,
//left指针则需要移动到在字符串s中第一个该字符出现的位置的右边的字符上
set.remove(s.charAt(left));
left++;
}
max = Math.max(max, set.size()); //比较先前的max和当前的滑动窗口的最大长度
}
return max;
}