【LeetCode 358】 Rearrange String k Distance Apart

/******************************
LeetCode 358 Rearrange String k Distance Apart
******************************/
/******************************
思想:
1.建立map,遍历字符串,统计字符出现的次数
2.定义一个数组nextPosition[26],存储字符下次可以出现的位置
3.字符串长度的循环体
每次寻找剩下字符中,个数最多的字符,且要满足的条件是 此处的位置大于nextPosition[i]
存在这样的字符,则加入结果字符
不存在的话,则返回"",说明不存在这样的字符串
注意维护nextPosition数组
时间复杂度:
n+26*n   n是字符串的长度
空间复杂度
O(1)
测试用例:
*******************************/
string rearrangeString(string str, int k)
{
	map<char, int> hashmap;
	int size = str.size();
	//建立hash表,统计每个字符出现的次数
	for (int ii = 0; ii < size; ++ii)
	{
		hashmap[str[ii]] += 1;
	}
	int nextPosition[26];//存储字符下次出现的位置
	memset(nextPosition, 0, sizeof(nextPosition));
	string result;
	int count = 0;//字符串长度
	for (int ii = 0; ii < size; ++ii)
	{
		//寻找剩下字符中个数最多的
		char ch = '\0';
		int max = 0;
		for (map<char, int>::iterator iter = hashmap.begin(); iter != hashmap.end(); ++iter)
		{
			if (count >= nextPosition[iter->first - 'a'] && iter->second>max)
			{
				max = iter->second;
				ch = iter->first;
			}
		}
 
		//判断是否找到
		if (max>0 && ch != '\0')
		{
			//找到了
			result += ch;
			hashmap[ch] -= 1;
			nextPosition[ch - 'a'] = count + k;//下次可以放的位置
			count++;
		}
		else
		{
			return "";
		}
 
	}
	return result;
 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值