反转括号中的字符串

反转括号中的字符串

题目描述

img

反转括号中的字符串,并返回没有括号的结果值。

题解

#include <iostream>
#include <stack>
using namespace std;

string helper(const string& s) {
    stack<string> strs;
    string res = "";
    for (int i = 0; i < s.size(); ++i) {
        if (s[i] == '(') {
            strs.push(res);
            res = "";
        }
        else if (s[i] == ')') {
            string tmp = strs.top();
            strs.pop();
            reverse(res.begin(), res.end());
            tmp += res;
            res = tmp;
        }
        else {
            res += s[i];
        }
    }
    return res;
}

string analysis(const string& s, int& index) {
    string res = "";
    while (index < s.size()) {
        if (s[index] == '(') {
            string tmp = analysis(s, ++index);
            reverse(tmp.begin(), tmp.end());
            res += tmp;
        }
        else if (s[index] == ')') {
            break;
        }
        else {
            res += s[index];
        }
        ++index;
    }
    return res;
}

int main() {
    int idx1 = 0;
    int idx2 = 0;
    int idx3 = 0;
    string s1 = "(u(love)i)";
    string s2 = "(abc)";
    string s3 = "(c(ba(ac))d)";
    cout << helper(s1) << endl; // iloveu
    cout << helper(s2) << endl; // cba
    cout << helper(s3) << endl; // dbacac
}

思路

栈实现

  1. 使用一个栈来暂存上一层的的结果。
  2. 当遇到 '(' 时,就将这一层处理的字符串 res 放入栈中,并置空 res,用于下一层的处理。
  3. 当遇到 ')' 时,就弹出上一层的结果,然后转置这一层处理的字符串,将上一层的结果和转置后的字符串拼接,作为上一层的继续处理字符串,也就是上述代码中的 res。

递归实现

  1. 当遇到字符时,就是递归的基本情况是给 res += s[i];
  2. 当遇到 '(' 时递归调用,返回的结果进行转置,并拼接到 res 上。
  3. 当遇到 ')' 时,结束递归,并返回。

posted on   LambdaQ  阅读(5)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示