用栈来存储字符,每一次遇到 ']' 时,就弹栈到栈顶为 '[' 为止,这样就得到了中括号内的字符,然后继续弹,得到次数即可。
最后按照次数与字符串在入栈
class Solution { public: string decodeString(const string &s) { stack<char> stk; for (int i = 0; i < s.size(); ++i) { if (s[i] != ']') { stk.push(s[i]); continue; } string temp; while (!stk.empty() && stk.top() != '[') { temp.push_back(stk.top()); stk.pop(); } stk.pop(); int cnt = 0, base = 1; while (!stk.empty() && stk.top() != '[' && stk.top() >= '0' && stk.top() <= '9') { cnt = (stk.top() - '0') * base + cnt; base *= 10; stk.pop(); } if (temp.empty()) continue; for (int j = 0; j < cnt; ++j) { for (int k = temp.size() - 1; k >= 0; --k) { stk.push(temp[k]); } } } string ret; while (!stk.empty()) { ret.push_back(stk.top()); stk.pop(); } reverse(ret.begin(), ret.end()); return ret; } };