扩展括号中的字符串

1样例

输入:3(A)  输出:AAA

输入:2(2{A}2[B])1(C) 输出:AABBAABBC

使用堆栈的解决方案:

 

#include<iostream>
#include<string>
#include<stack>
#include<vector>

using namespace std;

string expendBrackets(const string &str)
{
    int index = 0;
    int num = 0;
    stack<int> numStk;
    vector<string> strVec;
    stack<char> bracketStk;
    string temp;
    string res;
    string finalStr;
    string result;
    while (index < str.length())
    {
        if (str[index] >= '0'&&str[index] <= '9')
        {
            num = 10 * num + str[index] - '0';
            index++;
        }
        else if (str[index] == '(' || str[index] == '[' || str[index] == '{')
        {
            numStk.push(num);//将数字压栈
            bracketStk.push(str[index]);//将左括号压栈
            num = 0;
            index++;
        }
        else if (str[index] >= 'A'&&str[index] <= 'Z')
        {
            temp += str[index];
            index++;
        }
        else if (str[index] == ')' || str[index] == ']' || str[index] == '}')
        {
            if (!temp.empty())
            {
                strVec.push_back(temp);
                temp.clear();
            }
            int num = numStk.top();
            numStk.pop();
            bracketStk.pop();
            if (bracketStk.empty())
            {
                for (int j = 0; j < strVec.size(); j++)
                {
                    temp += strVec[j];
                }
                strVec.clear();
                strVec.push_back(temp);
                temp.clear();
            }
            for (int i = 0; i < num; i++)
            {
                res += strVec.back();
            }
            strVec.at(strVec.size() - 1) = res;
            res.clear();
            if (numStk.empty())
            {
                result = result+strVec.back();
                strVec.clear();
            }
            index++;
        }
    }
    return result;
}

int main()
{
    string res = expendBrackets("2(2(A))3(B)4(C)5(D)");//2(1(2(2{AB}))2(2(2(B))))2(2(2(C))2(D))
    cout << res <<endl;
    cin.get();
    return 0;
}

 

转载于:https://www.cnblogs.com/hust-coder/p/10747329.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值