给定两个字符串T和S,找出在S中包含字符串T的最小子字符串,要求时间复杂度为O(n)。
如果不存在最小窗口,则返回”“;
例如,
S = "ADOBECODEBANC"
T = "ABC"
返回的最小窗口是"BANC"
.
实验的代码如下所示:
#include<iostream> #include<string> #include<vector> using namespace std; string minWindow(string &S, string &T) { int Slen = S.length(); int Tlen = T.length(); if (Slen < Tlen || T.empty()) { return ""; } vector<int> ToBeFind(128, 0); vector<int> Found(128, 0); for (int i = 0; i != Tlen; ++i) { ToBeFind[T[i]]++; } int Count = Tlen; int first = 0; int last = 0; int minfirst = 0; int minlast = 0; int minlength = INT_MAX; Found[S[0]]++; if (Found[S[0]] <= ToBeFind[S[0]])//先比较第一个字符是为了处理T为单个字符的特例 { Count--; } while (true) { if (Count == 0) { while (Found[S[first]] > ToBeFind[S[first]]) { Found[S[first]] --; first++; } int length = last - first + 1; if (length < minlength) { minfirst = first; minlast = last; minlength = length; } } if (last < Slen) { last++; Found[S[last]]++; if (Found[S[last]] <= ToBeFind[S[last]]) { Count--; } } else { break; } } if (minlength == INT_MAX) { return ""; } return S.substr(minfirst, minlength); } int main() { string S1 = "ADOBECODEBANC"; string S2 = "ABC"; string S3 = "A"; cout << minWindow(S1, S2) << endl; cout << minWindow(S3, S2) << endl; system("pause"); return 0; }
实验结果如下所示:
时间: 2024-11-26 02:34:45