• PAT (Basic Level) Practice (中文) 1078 字符串压缩与解压 (20分) (字符转数字——栈存放)


    1.题目

    文本压缩有很多种方法,这里我们只考虑最简单的一种:把由相同字符组成的一个连续的片段用这个字符和片段中含有这个字符的个数来表示。例如 ccccc 就用 5c 来表示。如果字符没有重复,就原样输出。例如 aba 压缩后仍然是 aba

    解压方法就是反过来,把形如 5c 这样的表示恢复为 ccccc

    本题需要你根据压缩或解压的要求,对给定字符串进行处理。这里我们简单地假设原始字符串是完全由英文字母和空格组成的非空字符串。

    输入格式:

    输入第一行给出一个字符,如果是 C 就表示下面的字符串需要被压缩;如果是 D 就表示下面的字符串需要被解压。第二行给出需要被压缩或解压的不超过 1000 个字符的字符串,以回车结尾。题目保证字符重复个数在整型范围内,且输出文件不超过 1MB。

    输出格式:

    根据要求压缩或解压字符串,并在一行中输出结果。

    输入样例 1:

    C
    TTTTThhiiiis isssss a   tesssst CAaaa as
    

    输出样例 1:

    5T2h4is i5s a3 te4st CA3a as
    

    输入样例 2:

    D
    5T2h4is i5s a3 te4st CA3a as10Z
    

    输出样例 2:

    TTTTThhiiiis isssss a   tesssst CAaaa asZZZZZZZZZZ

    2.代码

    #include<iostream>
    #include<string>
    #include<cmath>
    #include<stack>
    #include<cstring>
    using namespace std;
    int main()
    {
    	char a, temp = '';
    	int count = 0;
    	string b;
    	cin >> a;
    	getchar();
    	getline(cin, b);
    	if (a == 'C')
    	{
    		for (int i = 0; i < b.length(); i++)
    		{
    			if (b[i] == temp)
    				count++;
    			if (b[i] != temp)
    			{
    				if (count > 0)
    					printf("%d%c", count + 1, b[i - 1]);
    				if (count == 0 && i != 0)
    					printf("%c", b[i - 1]);
    				temp = b[i];
    				count = 0;
    			}
    		}
    		if (count > 0)
    			printf("%d%c", count + 1, b[b.length() - 1]);
    		if (count == 0)
    			printf("%c", b[b.length() - 1]);
    	}
    	int k = 0, s = 0; stack<int>list;
    	bool last = false;//最后是不是数字
    	if (a == 'D')
    	{
    		for (int i = 0; i < b.length(); i++)
    		{
    			if (b[i]<'0' || b[i]>'9') { printf("%c", b[i]); continue; }
    			while (b[i] >= '0'&&b[i] <= '9')
    			{
    				list.push(b[i] - 48);
    				i++;
    			}
    			while (!list.empty())
    			{
    				s = list.top(); list.pop();
    				count += s*pow(10, k++);
    			}
    			if (i == b.length()) { last = true; break; }//最后是数字
    			for (int j = 0; j < count; j++)
    				printf("%c", b[i]);
    			count = 0; k = 0;
    		}
    			if(last)printf("%d", count);
    	}
    }
  • 相关阅读:
    HTTP 常见状态码
    SpringMVC 入门
    Maven 整合SSH框架
    SSH 框架整合总结
    Maven 整合SSH框架之pom.xml
    Maven 入门
    WebService 综合案例
    CXF 框架
    jQuery高级
    JavaScript补充:BOM(浏览器对象模型)
  • 原文地址:https://www.cnblogs.com/Jason66661010/p/12788912.html
Copyright © 2020-2023  润新知