LeetCode.395

原题:Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.

int calcSubstr(string str, int k){
	
	string tempStr = "";							//临时字符串 
	char tempChar = '0';							//临时字符 
	string now_str = str;							//清除一次字符后的字符串 
	int now_length = now_str.length();					//清除一次字符后的字符串长度 
	
	string markStr = "";							//符合出现小于k次的字符组合成的字符串 
	int repCount = 0;
	
	/*计算各字符出现次数,将少于k次的存于markStrRpe中*/
	while(now_length){
		tempChar = now_str[0];
		for(int i = 0; i < now_length; i++){
			if(tempChar != now_str[i]){
				tempStr += now_str[i];
			}
		}
		repCount = now_length - tempStr.length();
		if(repCount < k && repCount != 0){
			markStr += tempChar;
		}
		now_str = tempStr;
		now_length = tempStr.length();
		tempStr = "";
	}
	
	vector<int> index_mark;    //记录分割字符所在位置 
	
	/*找出分割字符在原字符串中的位置并记录在index_mark中*/
	for(int i = 0; i < str.length(); i++){
		for(int j = 0; j < markStr.length(); j++){
			if(str[i] == markStr[j]){
				index_mark.push_back(i);
				break;
			}
		}
	}
	
	int max = 0;
	int count = 0;
	
	if(index_mark.size()){
		tempStr = "";
		for(int i = 0; i < index_mark.size();){
			for(int j = count; j < str.length(); j++){
				if(j == index_mark[i]){
					i++;
					count = j + 1;
					break;
				}
				tempStr += str[j];
			}
			if(!tempStr.empty()){
				int temp = calcSubstr(tempStr, k);
				if(max < temp){
					max = temp;
				}
				tempStr = "";
			}
		}
		
		int last = index_mark[index_mark.size() - 1] + 1;
		if(last != str.length() - 1){
			int temp = calcSubstr(str.substr(last), k);
			if(max < temp){
				max = temp;
			}
		}
	}
	else{
		max = str.length();
	}
	
	return max;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值