利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。
给定一个string iniString为待压缩的串(长度小于等于3000),保证串内字符均由大小写英文字母组成,返回一个string,为所求的压缩后或未变化的串。
测试样例
“aabcccccaaa”
返回:”a2b…
class Zipper {
public:
//VC++测试结果正确!
int power(int sum, int n){
int temp=sum;
if(n==0) return 1;
else if(n==1) return sum;
else{
for(int i=1;i<n;i++)
sum*=temp;
return sum;
}
}
string zipString(string iniString) {
// write code here
string result;//保持结果的字符串
result.clear();
int i;
int count=0;
int len=iniString.size();
char t;//指示结果字符串中的当前字符
t=iniString[0];
for(i=0;i<=len;i++){//用len取“=”号的原因,字符串iniString结束时 iniString[len+1]='\0',与其它字符不等,
//故而可以进入随后的if语句进行count统计;如果len没有取"="将导致最后一个字符的统计数不能输出
if(t!=iniString[i]){
result+=t;
if(count>9){//当count不止一位数时,进行处理
int temp=count;
int tn=1;
int j;
while(temp>=10){//计算count的位数
temp=temp/10;
tn++;
}
for(j=tn-1;j>=0;j--){//从最高位开始,将各位数字依次加入result中
result+=count/(power(10,j))+'0';
count=count%(power(10,j));
}
//lenResult=lenResult+tn;
}else{
result+=count+'0';
}
count=1;
t=iniString[i];
}else{
count++;
}
}
if(result.size()<iniString.size()){
return result;
}else{
return iniString;
}
}
};