LintCode 32: Minimum Window Substring (同向雙指針好題)

  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.

解法1:
這題思路就是用同向雙指針,但是我覺得相當不容易。

  1. p1從0開始,p2先往右移動,一直到p1…p2之間的窗口覆蓋所有的target字母。然後p1再往右移動一個,若
    窗口已經不能覆蓋所有字母了,則p2又往右移動一個,直到邊界。
  2. count表示當前窗口(p1+1…p2)裏面還缺count個target的元素。所以一旦count>0,p2必須往右移動。
  3. if (mp[source[p1]] == 0) count++;即source[p1]是一個target裏面的元素,此時window罩不住target裏面的元素了。注意p1在p2後面,p2已經處理過了,所以mp[source[p1]]=0的話一定是一個target裏面的元素。
    代碼如下:
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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章