导航

最短文摘

Posted on 2013-10-09 10:14  wpzhongyq  阅读(107)  评论(0)    收藏  举报

用一个map保存当前区间chars中各字符出现的次数。如果要求区间不能出现chars以外的字符,则若pEnd字符不在chars之内时,相当于继续处理[pEnd+1:]数组。

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

string shortestSubString(string str, string chars){
    map<char,int> flag;
    for(size_t i=0; i<chars.size(); i++)
        flag[chars[i]]=0;
    size_t pBegin=0, pEnd=0;
    size_t targetLen=str.size()+1, targetBegin, targetEnd;
    while(true){
        while( pEnd<str.size() && ( !isAllExisted(flag) ) ){
            if( flag.find(str[pEnd])!=flag.end() )
                flag[str[pEnd]]++;
            pEnd++;
        }
        while( isAllExisted(flag) ){
            if( pEnd-pBegin<targetLen ){
                targetLen=pEnd-pBegin;
                targetBegin=pBegin;
                targetEnd=pEnd;
            }
            if( flag.find(str[pBegin])!=flag.end() )
                flag[str[pBegin]]--;
            pBegin++;
        }
        if(pEnd>=str.size())
            break;
    }
    if(targetLen==str.size()+1)
        return "-1";
    return str.substr(targetBegin, targetLen);
}