import java.util.Stack;

class Solution {
  private record StackEntry(int count, StringBuilder str) {
    @Override
    public String toString() {
      return new StringBuilder().repeat(str(), count()).toString();
    }
  }

  public String decodeString(String s) {
    var stack = new Stack<StackEntry>();
    stack.push(new StackEntry(1, new StringBuilder()));

    int count = 0;
    for (int i = 0; i < s.length(); ++i) {
      var c = s.charAt(i);

      if (c == '[') {
        stack.push(new StackEntry(count, new StringBuilder()));
        count = 0;
      } else if (c == ']') {
        var last = stack.pop();
        stack.peek().str().append(last);
      } else if (Character.isDigit(c)) {
        count *= 10;
        count += c - '0';
      } else {
        stack.peek().str().append(c);
      }
    }

    return stack.pop().toString();
  }
}