题目:统计重复字符串的个数,并输出。
示例输入: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