Cover image for LeetCode Hot 100 P394 Decode String

LeetCode Hot 100 P394 Decode String

Words 312
Views
Visitors

Timeline

Timeline

2026-03-18

init

Stack

Problem:

Example:ab2[cd3[ef]]How does the human brain read it?

  • Outer structureab + 2[ ... ]
  • Inner layercd + 3[ef]
  • Innermostef

Key point: each layer […] is an independent subproblem. This expression is essentially:

When we encounter[we must save the state:

  • What was the previous string?
  • What is the number of repetitions?

To summarize:

When encountering [ then push onto the stack and save the context,When encountering ] then pop from the stack and restore the context

The code is as follows:

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
#include <stack>#include <string>using std::stack;using std::string;class Solution {    public:        string decodeString(string s)        {                stack<int> times;                stack<string> strs;                string curr = "";                int num = 0, k;                for (char ch : s) {                        if (ch >= '0' && ch <= '9') {                                num = num * 10 + (ch - '0');                        } else if (ch == '[') {                                times.push(num);                                strs.push(curr);                                num = 0;                                curr = "";                        } else if (ch == ']') {                                k = times.top();                                times.pop();                                string prev = strs.top();                                strs.pop();                                string tmp;                                for (int i = 0; i < k; i++)                                        tmp += curr;                                curr = prev + tmp;                        } else { // alpha                                curr += ch;                        }                }                return curr;        }};#include <iostream>int main(){        Solution S;        string s1 = "2[abc]3[cd]ef";        string s2 = "3[a2[c]]";        string s3 = "2[2[y]pq]";        std::cout << S.decodeString(s1) << '\n';        std::cout << S.decodeString(s2) << '\n';        std::cout << S.decodeString(s3) << '\n';}
Loading comments…