Leetcode 76. Minimum Window Substring
题目

解法:sliding window
直接上leetcode 官方solution
- We start with two pointers, leftleft and rightright initially pointing to the first element of the string SS.
- We use the rightright pointer to expand the window until we get a desirable window i.e. a window that contains all of the characters of TT.
- Once we have a window with all the characters, we can move the left pointer ahead one by one. If the window is still a desirable one we keep on updating the minimum window size.
- If the window is not desirable any more, we repeat step ; 2step2 onwards.
python代码如下:
class Solution:
def minWindow(self, s: str, t: str) -> str:
if not t or not s:
return ''
dict_t = Counter(t)
required = len(dict_t)
l,r = 0,0
formed = 0
window_counts = {}
ans = float('inf'),None,None
while r<len(s):
character = s[r]
window_counts[character] = window_counts.get(character,0)+1
if character in dict_t and window_counts[character] == dict_t[character]:
formed += 1
while l<=r and formed==required:
character = s[l]
if r-l+1 < ans[0]:
ans = (r-l+1,l,r)
window_counts[character] -= 1
if character in dict_t and window_counts[character]<dict_t[character]:
formed -= 1
l += 1
r += 1
return '' if ans[0]==float('inf') else s[ans[1]:ans[2]+1]
C++代码如下:
class Solution {
public:
string minWindow(string s, string t) {
vector<int> count_t(128,0);
vector<int> count_window(128,0);
int required = 0;
for(int i=0;i<t.size();++i){
if(count_t[t[i]]==0) ++required;
++count_t[t[i]];
}
int l=0, r=0,formed=0;
int window_size = s.size()+1,final_l=0,final_r=0;
while (r<s.size()){
count_window[s[r]] = count_window[s[r]]+1;
if (count_window[s[r]]==count_t[s[r]]) ++formed;
while (l<=r && formed==required){
if (r-l+1 < window_size) {
window_size = r-l+1;
final_l = l;
final_r = r;
}
--count_window[s[l]];
if (count_window[s[l]] < count_t[s[l]]) --formed;
++l;
}
++r;
}
return window_size == s.size()+1? "":s.substr(final_l,final_r-final_l+1);
}
};
本篇博客主要介绍LeetCode第76题——最小覆盖子串的解题思路,使用滑动窗口算法进行求解。提供Python和C++两种语言的代码实现,并附有官方解决方案链接。

439

被折叠的 条评论
为什么被折叠?



