#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
string decodeString(const string &s) {
stack<char> stk;
bool hasBracket = false;
for (char i: s) {
if (i == '[') hasBracket = true;
stk.push(i);
}
if (!hasBracket) return s;
bool empty_stk_flag = false;
while (!empty_stk_flag) {
string non_repeated_str;
while (!stk.empty() && stk.top() != ']') {
non_repeated_str.push_back(stk.top());
stk.pop();
}
reverse(non_repeated_str.begin(), non_repeated_str.end());
vector<string> tokens_between_brackets;
while (!stk.empty()) {
if (stk.top() == ']') {
stk.pop();
string token;
while (!stk.empty() && stk.top() != ']' && stk.top() != '[') {
token += stk.top();
stk.pop();
}
reverse(token.begin(), token.end());
tokens_between_brackets.push_back(token);
} else {
int last_index = (int) tokens_between_brackets.size() - 1;
if (last_index >= 0) {
for (char j: tokens_between_brackets[last_index]) {
stk.push(j);
}
if (!tokens_between_brackets.empty()) {
tokens_between_brackets.pop_back();
}
}
break;
}
}
reverse(tokens_between_brackets.begin(), tokens_between_brackets.end());
string repeated_token;
while (!stk.empty() && stk.top() != '[') {
repeated_token.push_back(stk.top());
stk.pop();
}
reverse(repeated_token.begin(), repeated_token.end());
if (!stk.empty())
stk.pop(); //pop '['
string repeat_number_str;
while (!stk.empty() && isdigit(stk.top())) {
repeat_number_str += stk.top();
stk.pop();
}
reverse(repeat_number_str.begin(), repeat_number_str.end());
int repeat_number = stoi(repeat_number_str);
string remaining;
while (!stk.empty() && stk.top() != ']' && stk.top() != '[') {
remaining += stk.top();
stk.pop();
}
if (stk.empty())
empty_stk_flag = true;
reverse(remaining.begin(), remaining.end());
for (char i: remaining) {
stk.push(i);
}
for (int i = 0; i < repeat_number; ++i) {
for (char j: repeated_token) {
stk.push(j);
}
}
for (const auto &j: tokens_between_brackets) {
for (auto k: j) {
stk.push(k);
}
stk.push(']');
}
for (char i: non_repeated_str) {
stk.push(i);
}
}
char result[stk.size() + 1];
result[stk.size()] = '\0';
int i = stk.size() - 1;
while (!stk.empty()) {
result[i--] = stk.top();
stk.pop();
}
return result;
}
};
int main() {
auto result = Solution().decodeString("1[a2[c2[d]j]ii]");
for (char i : result) {
cout << i ;
}
cout << endl << "expected: acddjcddjii" << endl;
}