重复字符的压缩

  对输入字符串进行压缩,输入"aaabcccdde",输出"3ab3c2de",即对连续出现的字符进行压缩。

  解题思路:首先创建一个临时变量temp,给它赋值为第一个字符的值,从下一个字符开始遍历,如果等于temp,count++;如果不等于temp;则把此时temp出现的次数和temp存放在字符数组b中。(输出也行,不会多占用内存空间,空间复杂度为O(1)).

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
char* stringCompress(char a[])
{char temp=a[0];
    int len=strlen(a);
    //int count[len]={0};
    int count=1;
    //string str;
    char b[len+1];
    int j=0;
    for(int i=1;i<len;i++)
    {
        if(a[i]==temp)
            count++;
        else{
            if(count!=1)
              b[j++]=count+'0';
             b[j++]=temp;
             count=1;
            temp=a[i];
        }
    }
    if(count!=1)
      b[j++]=count+'0';
    b[j]=temp;
    b[++j]='';

    return b;
}
int main()
{
    char a[100];
    cin.getline(a,100);
    cout<<a<<endl;

    char* res=stringCompress(a);
    cout<<res<<endl;
    system("pause");
    return 0;
}

直接输出不再占用多余的内存空间,代码如下:

void stringCompress(char a[])
{
    //int mark=0;
    char temp=a[0];
    int len=strlen(a);
    //int count[len]={0};
    int count=1;
    //string str;
    char b[len+1];
    int j=0;
    for(int i=1;i<len;i++)
    {
        if(a[i]==temp)
            count++;
        else{
            if(count!=1)
              cout<<count;
             cout<<temp;
             count=1;
            temp=a[i];
        }
    }
    if(count!=1)
      cout<<count;
    cout<<temp;
}
原文地址:https://www.cnblogs.com/wft1990/p/6953409.html