c++ - 一种解压缩字符串的算法

标签 c++ algorithm

<分区>

我有一个类似于下面的 aa4bccc3d 的字符串,我需要将它转换为 aabbbbcccddd 我的解决方案有效,但我不知道如何恢复这样的情况: a25b 应解码为 abbbbbbbbbbbbbbbbbbbbbbbbb 或 125b 大小写。

string convert(string c) {

    string result = "";
    for (int i = 0; i < c.size(); i++) {
        if (c[i] >= 'a' && c[i] <= 'z') {
            result += c[i];
        } else if (c[i]-'0' >= 0 && c[i]-'0' <= 9) {
            if (i < c.size()) {
                int prevI = i;
                int nextJ = i;
                if (c[++nextJ] >= 'a' && c[++nextJ] <= 'z') {
                    for (int j = 0; j < c[prevI]-'0'; j++ {
                        result += c[prevI+1];
                    }    
                }
            }
        }
    }

    return result;
}

最佳答案

#include <iostream>
#include <string>
#include <algorithm> //max
#include <locale> //isdigit

std::string uncompress(const std::string & s) {
    int counter=0;
    std::string r;
    for(char c : s){
        if(std::isdigit(c)){
            counter=counter*10+c-'0';
        }
        else{
            for(int i=0;i<std::max(1,counter);++i ){
                r=r+c;
            }
            counter=0;
        }
    }
    return r;
}

int main() {
    // your code goes here
    std::cout << uncompress("aa12c") << "\n";
    return 0;
}

关于c++ - 一种解压缩字符串的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29239706/

相关文章:

c - 设计一个算法来判断是否存在这样一个键等于数组中其他两个键的总和

c++ - 解决二维数组中的迷宫

c++ - C++ 中的另一个静态数组初始化

c++ - 使用 C++ API 创建数组 expr

c++ - Matlab C++ - 接收动态大小输出类型 (emxArray_real_T)

c++ - 如何检查文件最后一行的 new_line 字符? C++

c++ - typedef 和非简单类型说明符

java - 使用二分搜索返回的缺失元素位置时的代码更清晰

algorithm - 有向图最著名的传递闭包算法是什么?

algorithm - 除了回溯,我如何在图中找到最长的路径?