/**
一串首尾相连的珠子(m个),有N种颜色(N<=10),
设计一个算法,取出其中一段,要求包含所有N中颜色,并使长度最短。
并分析时间复杂度与空间复杂度。
*/
#include <iostream>
#include <map>
#include <algorithm>
#include <string>
class state
{
public:
state(std::string str)
{
this->str=str;
sum=0;
std::for_each(str.begin(),str.end(),[&](const char& val)
{
if(color_map.find(val)==color_map.end())
color_map.insert(std::make_pair(val,0));
});
}
std::string get_shortest()
{
auto begin=str.begin();
auto end=str.begin();
auto min_begin=str.begin();
auto min_end=str.end();
int curmin=str.size();
while(end!=str.end())
{
if(!is_contained_all(*end,true))
{
++end;
continue;
}
while(begin<=end && is_contained_all(*begin,false))
++begin;
if((end-begin+1)<curmin)
{
curmin=end-begin+1;
min_begin=begin;
min_end=end;
}
++begin;
++end;
}
return std::string(min_begin,min_end+1);
}
private:
bool is_contained_all(const char& val,bool sig)
{
if(color_map.find(val)==color_map.end())
return sum==color_map.size();
if(sig)
{
if(color_map[val]==0)
++sum;
++color_map[val];
}
else
{
--color_map[val];
if(color_map[val]==0)
--sum;
}
return sum==color_map.size();
}
private:
std::map<char,int> color_map;
std::size_t sum;
std::string str;
};
int main(int argc,char* argv[])
{
state t(std::string("14638245802421746816792157204574801022"));
std::cout<<t.get_shortest()<<std::endl;
system("PAUSE");
return 0;
}
百度--包含所有珠子的最小串
最新推荐文章于 2014-11-11 16:26:09 发布