【PAT】B1078 字符串压缩与解压(20 分)

主函数接收下第一个字符,接着一个分支就转到两个函数中的一个
1.压缩简单,只要与下一个一样就只计数,如果不同了就直接输出
2.至于解压不知道数字是几位数,所以我直接用了sscanf,然后判断是几位数字,将指针知道后面的内容字符输出

#include<cstdio>
#include<string.h>
#include<algorithm>
#include<ctype.h>
using namespace std;
char str[2000]={'\0'};
int len;
void compress(){
    int num=0;
    for(int i=0;i<len;i++){
        if(str[i]==str[i+1]) num++;
        else{
            if(num==0)printf("%c",str[i]);
            else{
                printf("%d%c",num+1,str[i]);
                num=0;
            }
        }
    }
}
void Decompress(){
    int i=0;
    while(i<len){
        int temp=0;
        if(isdigit(str[i])) sscanf(&str[i],"%d",&temp);
        if(temp==0){
            printf("%c",str[i]);
        }else{
            if(temp/10==0) i+=1;
            else if(temp/100==0) i+=2;
            else if(temp/1000==0) i+=3;
            for(int j=0;j<temp;j++){
                printf("%c",str[i]);
            }
        }
        i++;
    }
}
int main(){
    char A;scanf("%c",&A);
    getchar();
    scanf("%[^\n]",str);
    len=strlen(str);
    if(A=='C') compress();
    else if(A=='D') Decompress();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hebust/p/9491358.html
今日推荐