最小子串覆盖

来源:互联网 发布:python lxml etree 编辑:程序博客网 时间:2024/05/28 06:07

题目描述

给定一个字符串source和一个目标字符串target,在字符串source找到包括所有目标字符串字母的子串。

 注意事项

如果在source没有这样的子串,返回"",如果有多个这样的子串,返回起始位置最小的子串。

样例

给出source = "ADOBECODEBANC"target = "ABC" 满足要求的解  "BANC"

思路

用一个大小为128的数组来存储每个字符出现的次数。遍历target,是数组相应的位置上加1。之后设置两个指针,begin和end,用于计算长度。当target的字母在source中出现时,counter减1,当counter减为0时,target中的全部字母已包含在source的子串中,接着我们比较子串的长度选出最小的即可。


代码

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        int map[128] = {0};        for (int i=0; i<target.size(); i++)            map[target[i]]++;        int counter = target.size(),begin = 0,end = 0,d = INT_MAX,head = 0;                while(end<source.size()){            if(map[source[end]]-- > 0)                counter--;            while(counter==0){                if(end-begin+1 <d){                    d = end-begin+1;                    head = begin;                }                if(map[source[begin]]++ >=0 ){                    counter--;                }                begin++;            }            end++;        }                return d == INT_MAX ? "" : source.substr(head,d);    }};