https://leetcode.com/problems/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.
class Solution {
public:
string minWindow(string s, string t) {
if(s.size() < t.size() || "" == t) {
return "";
}
int cint[256] = {0};
for(int i=0; i<t.size(); ++i) {
++cint[t[i]];
}
string minWin = "";
int findins[256] = {0};
int find = 0, n = t.size();
queue<int> idxes;
int st = -1, ed = -2;//ed < st means no window exits.
for(int i=0; i<s.size(); ++i) {
char c = s[i];
if(cint[c]) {
idxes.push(i);
if(st < 0) { // st not init
st = i;
}
ed = i;
++findins[c];
if(findins[c] <= cint[c]) {// first find s[i]
++find;
} else {
c = s[st];
while(!idxes.empty() && findins[c] > cint[c]) {
idxes.pop();
--findins[c];
st = idxes.front();
c = s[st];
}
}
if(find == n && ("" == minWin || ed - st + 1 < minWin.size())) {
minWin = s.substr(st, ed-st+1);
}
} // if cint[s[i]]
}
return minWin;
}
};public class Solution {
public String minWindow(String s, String t) {
if (s == null || s.length() == 0 || t == null || t.length() == 0) {
return "";
}
int[] tHas = new int[256];
for (int i = 0; i < t.length(); ++i) {
++tHas[t.charAt(i)];
}
String minWin = "";
int[] sFnd = new int[256];
int find = 0, n = t.length();
Queue<Integer> idxes = new LinkedList<Integer>();
int st = -1, ed = -2; // ed < st means no window exits.
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (tHas[c] > 0) {
idxes.offer(i);
if (st < 0) { // st not init
st = i;
}
ed = i;
++sFnd[c];
if (sFnd[c] <= tHas[c]) {// first find s[i]
++find;
} else {
c = s.charAt(st);
while (!idxes.isEmpty() && sFnd[c] > tHas[c]) {
idxes.poll();
--sFnd[c];
st = idxes.peek();
c = s.charAt(st);
}
}
if (find == n && ("".equals(minWin) || ed - st + 1 < minWin.length())) {
minWin = s.substring(st, ed+1);
}
} // if cint[s[i]]
}
return minWin;
}
}
本文介绍了一种在字符串S中寻找包含字符串T所有字符的最短子串的算法。通过使用滑动窗口技术和哈希表,该算法能在O(n)的时间复杂度内找到满足条件的最小子串。
770

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



