百度--包含所有珠子的最小串

/**
一串首尾相连的珠子(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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值