1. Single Character Stack Simulation
Intuition
Iterate character by character. Push characters onto stack until ] is encountered. Pop characters until [ to extract the target substring. Then pop preceding digits to form the number k. Repeat the substring k times and push back onto the stack. At the end, join everything in the stack.
When to apply: When conceptualizing the problem strictly as stack-based replacement.
Algorithm
- Create a stack of characters or strings.
- Iterate through the string: if char !=
], push to stack. - If char ==
], pop characters until[into a temporary stringsegment. - Pop the
[bracket. - Pop consecutive digit characters and calculate multiplier
k. - Repeat
segmentktimes and push the result back onto the stack. - After processing all characters, join all stack items.
Single Character Stack Simulation
2 of 2 questions left todayObservation: Push tokens onto stack until index 6 (']')
Observation: Push tokens onto stack until index 6 (']').
Decision: Stack contains ['3', '[', 'a', '2', '[', 'c']. Stop pushing and pop backwards until '['.
Invariant: The first encountered ']' always corresponds to the most deeply nested expression.
#include <iostream>#include <string>#include <vector>#include <algorithm> class Solution {public: std::string decodeString(std::string s) { std::vector<std::string> st; int i = 0; while (i < (int)s.size()) { if (s[i] != ']') { st.push_back(std::string(1, s[i])); i++; } else { std::string sub = ""; while (!st.empty() && st.back() != "[") { sub = st.back() + sub; st.pop_back(); } st.pop_back(); // remove __SF_TOKEN_A__ std::string numStr = ""; while (!st.empty() && isdigit(st.back()[0])) { numStr = st.back() + numStr; st.pop_back(); } int k = std::stoi(numStr); std::string repeated = ""; while (k--) repeated += sub; st.push_back(repeated); i++; } } std::string res = ""; for (const auto& str : st) res += str; return res; }}; int main() { Solution sol; std::cout << sol.decodeString("3[a2[c]]") << std::endl; // "accaccacc" return 0;}Time & Space Complexity
- Time complexity:
O(Max Output Length)— Every character in the final decoded string is created and pushed onto stack. - Space complexity:
O(Max Output Length)
Why Brute Force Doesn't Scale:
Using two explicit stacks avoids function call overhead and recursion limit issues.
Using StringBuilder in Java / reserving vector capacity avoids repeated allocations.