首页 > 试题广场 >

压缩字符串(一)

[编程题]压缩字符串(一)
  • 热度指数:6988 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2bc5a3。
1.如果只有一个字符,1不用写
2.字符串中只包含大小写英文字母(a至z)。

数据范围:
0<=字符串长度<=50000

要求:时间复杂度O(N)
示例1

输入

"aabcccccaaa"

输出

"a2bc5a3"
示例2

输入

"shopeew"

输出

"shope2w"
char* compressString(char* param ) {
    // write code here
    int len=strlen(param);
    int i,j,n=1,len_s;  
    char *result=(char*)calloc(len, sizeof(char));
    result[0]=param[0];
    for(i=1,j=1;i<=len;i++)
    {
        if(param[i]==param[i-1]) n=n+1;
        else 
        {
            if(n>1)
            {
                char *s=(char*)calloc(6, sizeof(char));
                for(int k=0;n;k++)
                {
                   s[k]='0'+n%10;
                    n=n/10;
                }
                n=1;
                len_s=strlen(s);
                for(;len_s;len_s--,j++)
                {
                    result[j]=s[len_s-1];
                }
                free(s);
            }
            result[j]=param[i];
            j++;        
        }
    }
    return result;
}
发表于 2022-08-31 21:46:10 回复(0)

问题信息

上传者:小小
难度:
1条回答 3756浏览

热门推荐

通过挑战的用户

查看代码