您的位置:首页 > 博客中心 > 互联网 >

字符串压缩

时间:2022-05-11 12:17

二、题目描述(40分):
通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
压缩规则:
1、仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc"。
2、压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"。

要求实现函数: 
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);

【输入】 pInputStr:  输入字符串
            lInputLen:  输入字符串长度
【输出】 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;

【注意】只需要完成该函数功能算法,中间不需要有任何IO的输入输出

示例 
输入:“cccddecc”   输出:“3c2de2c”
输入:“adef”     输出:“adef”
输入:“pppppppp” 输出:“8p”

这题还有点难,填数据时当时没想到可以先填后面再填前面...

#include
#include
#include
#include
using namespace std;
void itoa(int n, char *&str)
{
    char *p = str;
    char *p1 = str;
    char temp;
    int len = 0;
    if (n < 0)
    {
        *p++ = ‘-‘;
        n = -n;
    }
    do
    {
        *p++ = n % 10 + ‘0‘;
        n = n / 10;
        len++;
       // printf("n%d ",n);
    }while(n > 0);
   // printf("ss%d %s",len,p);
    *p-- = ‘\0‘;
    //printf("%d %s",len,p);
    //if(len % 2 == 1)
    //    len++;
    for( len /= 2; len > 0; len--){
         temp = *p;
        *p-- = *str;
        *str++ = temp;
    }
    str = p1;
}
void stringZip1(const char *pInputStr, long lInputLen, char *pOutputStr)
{
    const char *p = pInputStr;
    int j,num,s,i;
    j = 0;
    num = 1;
    p++;
    while( *p != ‘\0‘)
    {
        while( *p == *(p-1) && *p != ‘\0‘)
        {
            p++;
            num++;
        }
        if( num > 1)
        {
            s = 0;
            int k;
            int temp = num;
            while(num > 0)
            {
                num /= 10;
                s++;
            }
            for(i=j,k=0; k < s; i--,k++)
            {
                pOutputStr[i+s-1] = temp % 10 + ‘0‘;
                temp /= 10;
            }
            j += s;
            pOutputStr[j++] = *(p-1);
            num = 1;
            p++;
        }
        else
            {
                pOutputStr[j++] = *(p-1);
                p++;
            }
        }
    if (*(p-1) != *(p-2))
        pOutputStr[j++] = *(p-1);
    pOutputStr[j] = ‘\0‘;
    printf("%s\n",pOutputStr);

}
int main()
{
    char s[40],s1[40];
    char *s2 = (char*)malloc(sizeof(char) * 40);
    while(scanf("%s",s))
    {
        stringZip1(s,strlen(s),s1);
    }

}

gxlsystem.com,布布扣

 

貌似自己写的itoa没有用到,因为后来发现用了反而不好操作...

本类排行

今日推荐

热门手游