PAT Basic 1078 string compression and decompression (20 minutes)

There are many text compression methods, here we only consider the simplest kind of: a discrete segments with the same characters and the character number of this fragment containing the character represented. For example,  ccccc to use  5c to represent. If the character is not repeated, it is output. For example,  aba it continues to be compressed  aba.

Decompression method is, in turn, the shaped like  5c such a representation is restored  ccccc.

Your request that the need of compression or decompression, for a given string for processing. Here we simply assume that the original string is non-empty string entirely of English letters and spaces.

Input formats:

The first line of a given input character, if  C it means the following strings being compressed; if  D it means that the following character string to be decompressed. The second line gives need not be compressed or decompressed string of 1000 characters, with a carriage return at the end. The number of repeated characters in the title to ensure that the range of integers, and the output file is not less than 1MB.

Output formats:

Compression or decompression request string, and outputs the result on a line.

Sample Input 1:

C
TTTTThhiiiis isssss a   tesssst CAaaa as

Output Sample 1:

5T2h4is i5s a3 te4st CA3a as

Sample Input 2:

D
5T2h4is i5s a3 te4st CA3a as10Z

Output Sample 2:

TTTTThhiiiis isssss a   tesssst CAaaa asZZZZZZZZZZ
#include <iostream>
#include <vector>
using namespace std;
struct node{
    char ch;int val;
};
vector<node> v;
int main()
{
    char ch;string str;
    cin>>ch;getline(cin,str);
    getline(cin,str);
    if(ch=='C'){//压缩
        v.push_back({str[0],1});
        for(int i=1;i<str.length();i++)
            if(str[i]==str[i-1]) v[v.size()-1].val++;
            else v.push_back({str[i],1});
        for(int i=0;i<v.size();i++)
            if(v[i].val==1) printf("%c",v[i].ch);
            else printf("%d%c",v[i].val,v[i].ch);
    }else{//解压
        int coun=0;
        for(int i=0;i<str.length();i++){
            if(coun==0&&!isdigit(str[i])) v.push_back({str[i],1});
            else if(isdigit(str[i])) coun=coun*10+(str[i]-'0');
            else {
                v.push_back({str[i],coun});
                coun=0;
            }
        }
        for(int i=0;i<v.size();i++)
            while(v[i].val--) printf("%c",v[i].ch);
    }
    system("pause");
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/littlepage/p/11707220.html