码蹄集丨字符串的解码

文章提供了两种编程语言(Python和C++)实现的解码算法,该算法处理包含数字和方括号的字符串。通过输入字符串,程序能识别并解析内部的数字信息,进行相应的计算和字符串组合。
摘要由CSDN通过智能技术生成

在这里插入图片描述
在这里插入图片描述
B站老师思路讲解:https://www.bilibili.com/video/BV1r84y1E7TB/?t=1415.0&vd_source=3ae2a916df1bc5c1114c2bf3e95a2118

Python代码实现:

原文链接:https://blog.51cto.com/u_15745546/5950626

def main():
    s = input()
    n = len(s)
    arr = []
    mm = {}
    for i in range(n):
        if s[i] == '[':
            arr.append(i)
        elif s[i] == ']':
            mm[arr[-1]] = i
            arr.pop(-1)

    def decode(ii, jj):
        if ii > jj:
            return ""
        if ii == jj:
            return s[ii]

        if s[ii] == '[':
            x = ii + 1
            while x + 1 < jj and '0' <= s[x + 1] <= '9':
                x += 1

            k = int(s[ii + 1: x + 1])
            return decode(x + 1, mm[ii] - 1) * k + decode(mm[ii] + 1, jj)

        else:
            x = ii
            while x + 1 <= jj and s[x + 1] not in "[]":
                x += 1

            return s[ii: x + 1] + decode(x + 1, jj)

    print(decode(0, n - 1))


if __name__ == '__main__':
    main();

C++代码实现:

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

using namespace std;

string decode(string s, int ii, int jj, unordered_map<int, int>& mm) {
    if (ii > jj) {
        return "";
    }

    if (ii == jj) {
        return string(1, s[ii]);
    }

    if (s[ii] == '[') {
        int x = ii + 1;
        while (x + 1 < jj && s[x + 1] >= '0' && s[x + 1] <= '9') {
            x++;
        }
        int k = stoi(s.substr(ii + 1, x - ii));
        string sub_str = decode(s, x + 1, mm[ii] - 1, mm);
        string res = "";
        for (int i = 0; i < k; i++) {
            res += sub_str;
        }
        return res + decode(s, mm[ii] + 1, jj, mm);
    } else {
        int x = ii;
        while (x + 1 <= jj && s[x + 1] != '[' && s[x + 1] != ']') {
            x++;
        }
        return s.substr(ii, x - ii + 1) + decode(s, x + 1, jj, mm);
    }
}

int main() {
    string s;
    cin >> s;

    int n = s.length();
    vector<int> arr;
    unordered_map<int, int> mm;

    for (int i = 0; i < n; i++) {
        if (s[i] == '[') {
            arr.push_back(i);
        } else if (s[i] == ']') {
            mm[arr.back()] = i;
            arr.pop_back();
        }
    }

    cout << decode(s, 0, n - 1, mm) << endl;

    return 0;
}

提交测试结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Magneto_万磁王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值