Sliding Window

好题:

  • Minimum Window Substring

  • Longest substring without repeating characters

模板

  • maintain a window = [begin, end] -> s.substring(begin, end +1)

  • define what is a valid window

  • move end pointer one step forward per iteration

  • only move begin pointer when found a valid window

for (int end = 0; end < s.length(); end++) { 
    //proceed s.charAt(end)
    
    while window is still valid {
        //update res 
        //move begin pointer
    }
}

找最小window: while window is still valid

找最大window: while window is still invalid

为什么不用begin作iterator?

  1. 因为如果iterator begin pointer的话最后both begin and end need to move to the end, which means each char has been visited by exact 2 times.

  2. while if we iterate end pointer to the end, each char has been visited by at most 2 times(only when char is part of a valid window)

Minimum Window Substring

  • sliding window模板题,多练

  • move end pointer one step forward per iteration

  • only move begin pointer when found a valid window

Find All Anagrams in a string

  • sliding window end pointer模板

Longest substring without repeating characters

  • find max window的模板题

  • 重点在于how to define a valid window

  • while window is invalid

  • 组合题,一个思路

  • 和上一题的区别只是把2改成K

  • 从题目上看以为还是sliding window的思路,实际上是divide & conquer

  • 先cnt所有char ,然后顺序遍历a~z, 如果cnt[i] == 0, skip to next char.

  • if cnt[i] < k,说明最终返回的结果里肯定没有这个char,所以就遍历string找到这个char,然后recursive call s.substring(0, i) 和substring(i + 1),在返回的left和right中返回大的

  • 简单修改下sliding window模板

  • 每次先sum += nums[end], 然后checksum >= s的情况下, 再sum -= nums[begin++];

  • Time: O(N), Space: O(1)

  • 这题最直接的是用HashMap,O(N)& O(N),打败了67.39%

  • 还可以用sliding window的思路解题设一个cur指针

  • 建一个HashSet

  • 当cur > k的时候,每次先删除nums[cur - k - 1]

  • 再判断set.add(nums[cur])是否为false,从而判断是否contain duplicate within at most K distance,打败了97%

Last updated

Was this helpful?