天天看點

[LeetCode] #3 無重複字元的最長子串

[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;
    }
}