LeetCode 76 Minimum Window Substring (C++)
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 =
T =
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 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.
Solution C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | class Solution { public: string minWindow(string S, string T) { int needToFind[256] = {0}; int alreadyFound[256] = {0}; int count = 0; int slen = S.length(); int tlen = T.length(); for (int i = 0; i < tlen; ++i) { needToFind[T[i]] ++; } int mstart = 0; int maxlen = numeric_limits<int>::max(); bool found = false; int begin = 0; int end = 0; for (; end < slen; ++end) { if (needToFind[S[end]] == 0) continue; if (alreadyFound[S[end]] < needToFind[S[end]]) { count ++; } alreadyFound[S[end]] ++; if (count == tlen) { while (alreadyFound[S[begin]] == 0 || alreadyFound[S[begin]] > needToFind[S[begin]]) { if (alreadyFound[S[begin]] > needToFind[S[begin]]) alreadyFound[S[begin]] --; ++ begin; } if (end - begin + 1 < maxlen) { found = true; maxlen = end - begin + 1; mstart = begin; } } } if (!found) return ""; return S.substr(mstart, maxlen); } }; |