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

知识点:

总结:

posted @ 2021-09-22 11:28  1243741754  阅读(36)  评论(0编辑  收藏  举报