【安卓】腾讯2020校园招聘-后台

1. [编程题]压缩算法

解题思路

本题是对递归思想的考察。根据题意抽取出递归函数的行为:
每次读入一个字符,直到遇到]或输入结束;对每次读入的字符进行判断,如果是大写字母,就准备输出;如果是[,就接下来读入重复次数count|,对于剩下的输入,递归调用decompress()获取被重复的字符串,然后将该字符串重复count次;最后返回所有待输出的字符串。可以用stringstream来实现字符串的拼接。

AC代码

#include <iostream>
#include <string>
#include <sstream>

std::string decompress() {
    std::ostringstream ss;
    char c;
    int count;
    while (std::cin >> c) {
        if (c >= 'A' && c <= 'Z') {
            ss << c;
        } else if (c == '[') {
            std::cin >> count;
            std::cin >> c;
            std::string tmp = decompress();
            while (count--) {
                ss << tmp;
            }
        } else if (c == ']') {
            break;
        }
    }
    return ss.str();
}

int main() {
    std::cout << decompress();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/huzheyu/p/android-tencent-2020.html