划分宝石问题(2017搜狐笔试题)

同学笔试,帮做了一道算法,题目如下:


分析:我想到的首先是判断 这个学者能否得到宝石,也就是要求ABCDE必须至少都出现一次。

如果没有的话,直接得不到宝石,返回0,。否则,就是能得到宝石,那么我们仅需要找两个宝石之间的最大间隔就可以了,需要注意的点就是项链是环形的,因此我们需要记录第一个宝石的位置和最后一个宝石的位置即可。代码如下,因为时间仓促,代码比较乱,各位见谅。


思路好像错了。


int getMoreBaoshi(string str){
	if (str.length() < 0)	return 0;
	int cnt = 0, res = 0;
	int end = 0;
	map<char, int> map;
	map['A'] = 1;
	map['B'] = 1;
	map['C'] = 1;
	map['D'] = 1;
	map['E'] = 1;
	while (end < str.length()){
		if (map[str[end]] < 2 && map[str[end]] >= 1){
			cnt++;
			map[str[end]]++;
		}
		end++;
	}
	if (cnt < 5){//得不到宝石
		res = 0;
		return res;
	}
	else{//可以得到宝石
		int start = 0,end=0,maxn = 0,first=0;
		while (start < str.length()){
			if (map[str[start]] >= 1)
			{
				first = start;
				start++;
				break;
			}
		}
		while (end<str.length()){
			if (map[str[end]] >= 1){//为宝石中的一种
				if (end - start - 1>=maxn){
					maxn = max(maxn, end - start - 1);
				}
				start = end;
			}
			end++;
		}
		int tmp = str.length() - start + first-1;
		maxn = max(tmp, maxn);
		return maxn;
	}
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值