#include <cstring>
#include <iostream>
#include <utility>
using namespace std;
// 字符串翻转
void reverse(char* start, char* end)
{
while(start < end)
{
swap(*start++, *end--);
}
}
// 将数字转换成字符串存储到numStr中
// 返回被转换的数字串长度
int setNum(char* numStr, int num)
{
if(num <= 1)
{
return 0;
}
char* p = numStr;
while(num != 0)
{
*p++ = num % 10 + '0';
num /= 10;
}
reverse(numStr, p - 1);
return p - numStr;
}
// 原地压缩字符串
void compress(char str[], int len)
{
char* compPtr = str; // 可用于存放压缩字符的地址
char preChar = '\0';
int sameCount = 1;
for(int i = 0; i <= len; ++i)
{
if(str[i] == preChar)
{
++sameCount;
}
else
{
if(preChar != '\0')
{
*compPtr++ = preChar;
}
if(sameCount > 1) // 压缩连续相同长度大于1的字符串
{
compPtr += setNum(compPtr, sameCount);
}
sameCount = 1;
}
preChar = str[i];
}
*compPtr = '\0';
}
int main(int argc, char* argv[])
{
char str[] = "kkmnqaaabbbbcdefffffffffffffffffffff";
int len = strlen(str);
cout << "压缩前:" << str << endl;
compress(str, len);
cout << "压缩后:" << str << endl;
return 0;
}
运行结果:
压缩前:kkmnqaaabbbbcdefffffffffffffffffffff
压缩后:k2mnqa3b4cdef21