Lintcode_32 Minimum Window Substring

本文介绍了一种在源字符串中寻找包含目标字符串所有字符的最短子串的方法,并提供了具体的实现思路与代码示例。该算法通过统计目标字符串中各字符出现次数,在源字符串中逐个匹配并更新窗口范围,最终确定最小覆盖子串。

Given a string source and a string target, find the minimum window in source which will contain all the characters in target.

Clarification

Should the characters in minimum window has the same order in target?

  • Not necessary.
Example

For source = "ADOBECODEBANC", target = "ABC", the minimum window is "BANC"

Challenge 

Can you do it in time complexity O(n) ?

思路是先统计目标中的每个字符出现了多少次,然后在需检测的string中每读到一个目标字符,就检查下头部有木有可以删去的

的字符,统计长度最小值, 用hashmap实现:

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<pair<char,int>> vec;
    unordered_map<char, int> map_t;
    unordered_map<char, int> map_s;
    unordered_set<char> set_for_s;
    string res="";
    int len_s=0;
    int len_t=0;
    int len=INT_MAX;
    for (int i=0;i<target.size();i++) {
        if (map_t.find(target[i]) == map_t.end()) {
            map_t[target[i]]=1;
            len_t++;
        }
        
        else
            map_t[target[i]]= map_t[target[i]]+1;
    }
    
    
    for (int i = 0; i<source.size();i++) {
        if (map_t.find(source[i])!= map_t.end()) {
            vec.push_back(make_pair(source[i],i));
            if (map_s.find(source[i]) != map_s.end()) {
                map_s[source[i]]=map_s[source[i]]+1;
            } else {
                map_s[source[i]]=1;
            }
            if (map_s[source[i]]>= map_t[source[i]] && set_for_s.find(source[i])== set_for_s.end()) {
                set_for_s.insert(source[i]);
                len_s++;
            }
                
            
            
            char c=vec[0].first;
            while (map_s[c]>map_t[c]) {
                map_s[c]=map_s[c]-1;
                vec.erase(vec.begin());
                c=vec[0].first;
            }

            
            if (len_s == len_t) {
                int l = vec[vec.size()-1].second - vec[0].second + 1;
                if (l<len){
                    len=l;
                    res=source.substr(vec[0].second, l);
                }
            }
        }
    }
    
    return res;
 }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值