LintCode 32: Minimum Window Substring (with good title to the two-pointer)

  1. Minimum Window Substring
    中文English
    Given two strings source and target. Return the minimum substring of source which contains each char of target.

Example
Example 1:

Input: source = “abc”, target = “ac”
Output: “abc”
Example 2:

Input: source = “adobecodebanc”, target = “abc”
Output: “banc”
Explanation: “banc” is the minimum substring of source string which contains each char of target “abc”.
Example 3:

Input: source = “abc”, target = “aa”
Output: “”
Explanation: No substring contains two ‘a’.
Challenge
O(n) time

Notice
If there is no answer, return “”.
You are guaranteed that the answer is unique.
target may contain duplicate char, while the answer need to contain at least the same number of that char.

Solution 1:
This question is to use the same idea to double-pointer, but I think it was not easy.

  1. p1 starting from 0, p2 to move to the right until the window between p1 ... p2 cover all the target letters. Then a p1 then move to the right, if the
    window can not cover all the letters, then p2 and a move to the right, to the border.
  2. count represents the current window (p1 + 1 ... p2) inside the still missing elements of count target. So once count> 0, p2 must move to the right.
  3. if (mp [source [p1] ] == 0) count ++; i.e. source [p1] is an element which target, target this time window could not cover the inside of the element. Note that in the back p1 p2, p2 has been processed, so mp [source [p1]] = 0, then there must be an element target.
    code show as below:
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) {
        int ns = source.size();
        int nt = target.size();
        
        map<char, int> mp;
        for (int i = 0; i < nt; ++i) {
            mp[target[i]]++;
        }
        int count = mp.size();
        
        int p1 = 0, p2 = 0;
        int minLen = INT_MAX;
        string minResult;
        
        while(p1 < ns) {
            while(p2 < ns && count > 0) {
                mp[source[p2]]--;
                if (mp[source[p2]] == 0) count--;
                p2++;
                if (count == 0) break;
            }
            
            if (count == 0) {
                int curWinSize = p2 - p1;// + 1;
                if (curWinSize < minLen) {
                    minLen = curWinSize;
                    minResult = source.substr(p1, curWinSize);
                }
            }
    
            if (mp[source[p1]] == 0) count++;
            mp[source[p1]]++;
            p1++;
        }
        
        return minResult;
    }
};
Published 577 original articles · won praise 21 · views 80000 +

Guess you like

Origin blog.csdn.net/roufoo/article/details/102996827