Medium
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
屬于滑動窗口那種Two Pointers的題, 維持l, r兩個指針,每次遇到沒有出現過的字符,就加入到set里面,并且向右擴展窗口;遇到出現過的字符,就要縮小窗口,從左邊開始刪除,知道刪完這個重復的元素,那么這時候set里面就沒有該元素了,又可以進行新的窗口擴展。
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0){
return 0;
}
int l = 0;
int r = 0;
int maxLen = 0;
HashSet<Character> set = new HashSet<>();
while (r < s.length() && l < s.length()){
if (!set.contains(s.charAt(r))){
set.add(s.charAt(r));
maxLen = Math.max(maxLen, r - l + 1);
r++;
} else {
set.remove(s.charAt(l));
l++;
}
}
return maxLen;
}
}