Sliding Window
Template
Time O(n)
int j = 0
for i in range(n):
while j<n && array 不滿足條件
j+=1
拓寬條件
if array 滿足條件
看是不是最優的
num[i]移出array3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
T: O(2n)
def lengthOfLongestSubstring(self, s: str) -> int:
record = set()
res = 0
i, j = 0, 0
while j < len(s):
while j < len(s) and s[j] not in record:
record.add(s[j])
j+=1
res = max(res, j-i)
record.remove(s[i])
i+=1
return resT: O(n), S: O(n)
340 Longest Substring with At Most K Distinct Characters
Given a string s, find the length of the longest substring T that contains at most k distinct characters.
利用map的size判斷k的數量
若超過找出left most character 的index
76. Minimum Window Substring
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC"
209. Minimum Size Subarray Sum
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3] Output: 2
Init i=0 and left=0, iterate over nums
862. Shortest Subarray with Sum at Least K
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.
If there is no non-empty subarray with sum at least K, return -1.
這題跟209的差異是num可能為負數
用一個dequeue紀錄 sum and index, dequeue in increasing order by sum
Update if we can find total - sum >= k, and kind updating to shorten the distant
395. Longest Substring with At Least K Repeating Characters
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.
For loop n char, 代表每次check 只帶有 n char 的longest substring 的ans
2 counter: num of unique char and num of char more than k
只有在 count unique char == num of unique char && count of unique char == num of char more than k 才update
O(26 * n)
Last updated
Was this helpful?