您的位置:首页 > 其它

字符串原地压缩

2012-09-03 22:27 218 查看
题目:将字符串原地压缩,比如"eeeeeaaaff"压缩为 "e5a3f2"。

答:

#include "stdafx.h"
#include <iostream>

using namespace std;

//字符串原地压缩
void CompressString(char *str)
{
if (NULL == str)
{
return;
}
int count = 0;
char *newStr = str;
char ch = *str;
while (*str != '\0')
{
if (*str != ch)
{
*newStr++ = ch;
if (count > 1) //当字符只出现一次时,1省略不写
{
*newStr++ = '0' + count;
}
count = 1;
ch = *str;
}
else
{
count++;
}
str++;
if (*str == '\0')
{
*newStr++ = ch;
if (count > 1) //当字符只出现一次时,1省略不写
{
*newStr++ = '0' + count;
}
}
}
*newStr = '\0';
}

int _tmain(int argc, _TCHAR* argv[])
{
char src[]  = "eeeeeaaaff";
CompressString(src);
cout<<src<<endl;

cout<<endl;
return 0;
}


界面运行如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: