统计重复字符串的个数

题目:统计重复字符串的个数,并输出。

示例输入:abcdef

示例输出:a1b1c1d1e1f1

示例输入:abbbbbbbbbbbcc

示例输出:a1b11c2

实现代码如下:

#ifndef STRREPEAT_H
#define STRREPEAT_H
#include <string.h>
#include <stack>
#include <iostream>
void StrRepeat(char* str){
	if(str==NULL)
		return;
	char* pre=str;//指向前一字符
	char* cur=(str+1);//指向后一字符
	char *result=new char[strlen(str)*2];//申请存储结果的空间
	int k=0;
	int times=1;//初始值为1
	std::stack<int> bitStack;//用于处理times>10的情况
	while(*cur!='\0'){//循环条件
		if(*cur==*pre)//相等则次数++
			++times;
		else{//处理不相等的情况
			result[k++]=*pre;
			while(times!=0){//处理times>10的情况
				bitStack.push(times%10);
				times=times/10;
			}
			while(!bitStack.empty()){
				result[k++]=bitStack.top()+'0';
				bitStack.pop();
			}
			times=1;//重置times
		}
		pre=cur;//后移指针
		cur=cur+1;
	}
	result[k++]=*pre;//处理最后一种字符,因为循环退出时最后一种字符未处理
	while(times!=0){//处理times>10的情况
		bitStack.push(times%10);
		times=times/10;
	}
	while(!bitStack.empty()){
		result[k++]=bitStack.top()+'0';
		bitStack.pop();
	}
	result[k]='\0';//字符串结尾空字符
	std::cout<<result<<std::endl;
}

void TestStrRepeat(){
	char str[100];
	while(std::cin>>str){
		StrRepeat(str);
	}
}
#endif

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值