您的位置:首页 > 其它

最小子串覆盖

2018-01-28 17:34 169 查看
给定一个字符串source和一个目标字符串target,在字符串source中找到包括所有目标字符串字母的子串。


 注意事项


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

您在真实的面试中是否遇到过这个题? 

Yes

说明

在答案的子串中的字母在目标字符串中是否需要具有相同的顺序?
——不需要。
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

        vector<int> map(128,0);

        for (auto c : target) map[c]++;//计算target中每个字母的个数

        int counter = target.size(),begin = 0,end = 0,d = INT_MAX,head = 0;

        while (end < source.size()) {//如果末尾大于或者等于source的大小退出循环

            if (map[source[end++]]-- > 0) counter--;//计算末尾的位置

            while (counter == 0) {

                if (end - begin < d) {//选出最短的字串

                    d = end - begin;

                    head = begin;

                }

                if (map[source[begin++]]++ == 0) counter++;//计算头的位置

            }

        }

        return d == INT_MAX ? "" : source.substr(head,d);

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: