用一个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); }
浙公网安备 33010602011771号