https://leetcode.com/problems/decode-string/description/
class Solution { public: string decodeString(const string &s, int &idx) { string res; int num = 0; for (; idx < s.length(); idx++) { if (isdigit(s[idx])) { num = num * 10 + s[idx] - '0'; } else if (s[idx] == '[') { idx++; string sub = decodeString(s, idx); for (int i = 0; i < num; i++) { res += sub; } num = 0; } else if (s[idx] == ']') { return res; } else { res.push_back(s[idx]); } } return res; } string decodeString(string s) { int idx = 0; return decodeString(s, idx); /* stack<int> si; stack<string> ss; string cur_str=""; int cur_num = 0; for (int idx = 0; idx < s.length(); idx++) { if (isdigit(s[idx])) cur_num = cur_num * 10 + s[idx] - '0'; else if (s[idx] == '[') { si.push(cur_num); ss.push(cur_str); cur_str = ""; cur_num = 0; } else if (s[idx] == ']') { int prev_num = si.top(); string prev_str = ss.top(); si.pop(); ss.pop(); while (prev_num-- > 0) prev_str += cur_str; cur_str = prev_str; cur_num = 0; } else cur_str.push_back(s[idx]); } return cur_str; */ /* stack<int> si; stack<string> st; int idx = 0; while (idx < s.length()) { if (isdigit(s[idx])) { int num = 0; while (isdigit(s[idx])) { num = num * 10 + s[idx] - '0'; idx++; } si.push(num); } else if (s[idx] == ']') { string cur; while (st.top() != "[") { cur = st.top() + cur; st.pop(); } st.pop(); // pop [ int num = si.top(); si.pop(); string curRes; while (num-- > 0) curRes += cur; st.push(curRes); idx++; } else if (s[idx] == '[') { st.push("["); idx++; } else { string cur; while (s[idx] != 0 && !isdigit(s[idx]) && s[idx] != '[' && s[idx] != ']') cur.push_back(s[idx++]); st.push(cur); } } string res; while (!st.empty()) { res = st.top() + res; st.pop(); } return res; */ } };