[LeetCode] 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).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC"
.
Note:
If there is no such window in S that covers all characters in T, return the emtpy string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
双指针思想,尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的
1 class Solution { 2 private: 3 int count1[256]; 4 int count2[256]; 5 public: 6 string minWindow(string S, string T) { 7 // Start typing your C/C++ solution below 8 // DO NOT write int main() function 9 if (T.size() == 0 || S.size() == 0) 10 return ""; 11 12 memset(count1, 0, sizeof(count1)); 13 memset(count2, 0, sizeof(count2)); 14 15 for(int i = 0; i < T.size(); i++) 16 { 17 count1[T[i]]++; 18 count2[T[i]]++; 19 } 20 21 int count = T.size(); 22 23 int start = 0; 24 int minSize = INT_MAX; 25 int minStart; 26 for(int end = 0; end < S.size(); end++) 27 { 28 if (count2[S[end]] > 0) 29 { 30 count1[S[end]]--; 31 if (count1[S[end]] >= 0) 32 count--; 33 } 34 35 if (count == 0) 36 { 37 while(true) 38 { 39 if (count2[S[start]] > 0) 40 { 41 if (count1[S[start]] < 0) 42 count1[S[start]]++; 43 else 44 break; 45 } 46 start++; 47 } 48 49 if (minSize > end - start + 1) 50 { 51 minSize = end - start + 1; 52 minStart = start; 53 } 54 } 55 } 56 57 if (minSize == INT_MAX) 58 return ""; 59 60 string ret(S, minStart, minSize); 61 62 return ret; 63 } 64 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】