Clarification

Should the characters in minimum window has the same order in target?

  • Not necessary.

Example

For source ="ADOBECODEBANC", target ="ABC", the minimum window is"BANC"

class Solution {
public:    
    /**
     * @param source: A string
     * @param target: A string
     * @return: A string denote the minimum window
     *          Return "" if there is no such a string
     */
    string minWindow(string &source, string &target) {
        // write your code here
        if (source == "" || target == "") {
            return "";
        }

        int sLen = source.length();
        int tLen = target.length();

        vector<int> tHash(256, 0);
        vector<int> sHash(256, 0);

        for (int i = 0; i < tLen; i++) {
            tHash[target[i]]++;
        }

        int start = 0;
        int end = 0;
        int minLen = INT_MAX;
        string minStr = "";

        for (;start < sLen; start++) {
            while (end < sLen && !isValid(tHash, sHash)) {
                sHash[source[end]]++;
                end++;
            }
            if (isValid(tHash, sHash)) {
                if (end - start < minLen) {
                    minStr = source.substr(start, end - start);
                    minLen = end - start;
                }
            }
            sHash[source[start]]--;
        }

        return minStr;
    }

    bool isValid(vector<int>& tHash, vector<int>& sHash) {
        for (int i = 0; i < 256; i++) {
            if (tHash[i] > sHash[i]) {
                return false;
            }
        }
        return true;
    }
};

results matching ""

    No results matching ""