滑动窗口的应用

一般地,求数组或字符串的最值问题,都可以使用滑动窗口。

滑动窗口的最大特点:有效利用已有的中间结果,天然地适合解决最值问题。

举个例子:

3. Longest Substring Without Repeating Characters

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set set = new HashSet<>();
        int ans = 0, i = 0, j = 0;
        while (i < n && j < n) {
            // try to extend the range [i, j]
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                ans = Math.max(ans, j - i);
            }
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }
}

 

你可能感兴趣的:(算法,滑动窗口的应用)