Skip to main content
Back to problems
#394
Medium Algorithms

Decode string

String Stack Recursion
62.3% acceptance
Jan 12, 2026
13925
699
Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4]. The test cases are generated so that the length of the output will never exceed 105.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn decode_string(s: String) -> String {
    let mut stack = Vec::new();
    let mut current_str = String::new();
    let mut current_num = 0;
    
    for ch in s.chars() {
      match ch {
        '0'..='9' => {
          current_num = current_num * 10 + ch.to_digit(10).unwrap() as usize;
        }
        '[' => {
          stack.push((current_str.clone(), current_num));
          current_str.clear();
          current_num = 0;
        }
        ']' => {
          let (prev_str, num) = stack.pop().unwrap();
          current_str = prev_str + &current_str.repeat(num);
        }
        _ => {
          current_str.push(ch);
        }
      }
    }
    
    current_str
  }
}