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;
    }
};
发布了577 篇原创文章 · 获赞 21 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/102996827