sundeepblue
4/17/2014 - 3:29 PM

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 comple

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.

#include <iostream>
#include <string>
#include <unordered_map>
#include <climits>
#include <vector>
using namespace std;

string minimum_window_substring(const string &s, const string &p) {
    if(p.empty() || s.empty() || s.size() < p.size()) return "";
    
    int left = 0, right = 0, ns = s.size(), np = p.size();
    int start_pos = 0, min_len = INT_MAX;
    
    vector<int> total(256, 0), sofar(256, 0);
    
    for(char c : p) total[c]++;   //      should be p not s !!!!!!!
    
    int curr_len = 0;
    for(; right < ns; right++) {
        char c = s[right];
        if(total[c] == 0) continue;
        else sofar[c]++;
        if(sofar[c] <= total[c]) curr_len++;
        
        while (curr_len == np) {
            char ch = s[left];
            if(total[ch] == 0) left++;
            else if (sofar[ch] > total[ch]) {
                sofar[ch]--;
                left++;
            } else break;
        }
        if(curr_len == np) {
            if(min_len > right - left + 1) {
                min_len = right - left + 1;
                start_pos = left;
            }
        }
    }
    if(curr_len < np) return "";
    return s.substr(start_pos, min_len);    
}

int main()
{
   cout << minimum_window_substring("aaabcdfefbbcf", "bcf");
   return 0;
}