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; }