文章

3. 无重复字符的最长子串

问题3 无重复字符的最长子串 ★☆☆☆☆

https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

滑动窗口的解法可以从暴力解法的思路中得到启发。比如说使用暴力解法,我们遍历n次,每次以s[i]为起点开始遍历直到碰到了重复字符s[j],本次遍历结束,然后开始以s[i+1]为起点开始下一轮遍历。这样操作的问题在哪呢?就在于下一轮遍历以s[i+1]为起点,这样就太笨了。因为s[i]到s[j-1]是确定没有重复字符的,假设s[j]和s[i]到s[j-1]中的某个s[k]是重复的,那么至少应该从s[k+1]开始下一轮遍历,这样就减少了很多重复计算。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    public int lengthOfLongestSubstringWithoutRepeatingCharacters(String s) {
        int len = s.length();

        Map<Character, Integer> index = new HashMap<>();

        int max = 0;
        int left = 0;
        for (int right = 0; right < len; right++) {
            char c = s.charAt(right);
            if (index.containsKey(c)) {
                int lastIndex = index.get(c);
                if (lastIndex + 1 > left) {
                    left = lastIndex + 1;
                }
            }
            index.put(c, right);
            max = Math.max(max, right - left + 1);
        }

        return max;
    }

在 LeetCode 查看

本文由作者按照 CC BY 4.0 进行授权