最短摘要

从一个长字符串中查找包含给定字符集合的最短子串。例如,长串为“aaaaaaaaaacbebbbbbdddddd dcccccc”,字符集为{abcd},那么最短子串是“acbebbbbbd”。如果将条件改为“包含且只包含给定字符集合”,你的算法和实现又将如何改动。

#include <map>
#include <set>
#include <string>
#include <iostream>
using namespace std;

bool is_all_included(map<char,int>& keywords_count_map){
    for(map<char,int>::iterator it =keywords_count_map.begin(); it != keywords_count_map.end();++it){
        if(0 == it->second){
            return false;
        }
    }
    return true;
}

string shortest_abstract(string text, const set<char>& keywords){
    map<char,int> keywords_count_map;
    for(set<char>::iterator it = keywords.begin(); it != keywords.end(); ++it){
        keywords_count_map[*it] = 0;
    }
   
    int length =text.length();
    int shortest_length = length;
    int begin =0, end = 0;
    int abstract_begin = -1, abstract_end = -1;

    for(;;){
        while(!is_all_included(keywords_count_map) && end < length){
            char key = text.at(end);
            if(keywords_count_map.find(key) != keywords_count_map.end()){
                keywords_count_map[key] += 1;
            }
            ++end;
       }

       while(is_all_included(keywords_count_map)){
           if(end - begin < shortest_length){
               shortest_length = end - begin;
               abstract_begin = begin;
               abstract_end = end;
           }
           char key = text.at(begin);
           if(keywords_count_map.find(key) != keywords_count_map.end()){
               keywords_count_map[key] -= 1;
           }
           ++begin;
       }

       if(end >= length){
           break;
       }
    }

    if(abstract_begin >=0 && abstract_end >=0){
        return text.substr(abstract_begin,abstract_end-abstract_begin);
    }
	    
    return string("-1");
}

int main(){
    string text= "aaaaaaaaaacbebbbbbdddddddcccccc";
    set<char> s;
    s.insert('a');
    s.insert('b');
    s.insert('c');
    s.insert('d');
    string o =shortest_abstract(text,s);
    cout << o << endl;
    return-1;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值