Tutorialspoint
Problem
Solution
Submissions

Decode String

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program to decode a run-length encoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets should be repeated exactly k times. You may assume that the input string is always valid with properly nested brackets.

Example 1
  • Input: s = "3[a]2[bc]"
  • Output: "aaabcbc"
  • Explanation:
    •  Step 1: "3[a]" means repeat "a" 3 times, resulting in "aaa".
    •  Step 2: "2[bc]" means repeat "bc" 2 times, resulting in "bcbc".
    •  Step 3: Concatenate the results: "aaa" + "bcbc" = "aaabcbc".
Example 2
  • Input: s = "2[abc]3[cd]ef"
  • Output: "abcabccdcdcdef"
  • Explanation:
    •  Step 1: "2[abc]" means repeat "abc" 2 times, resulting in "abcabc".
    •  Step 2: "3[cd]" means repeat "cd" 3 times, resulting in "cdcdcd".
    •  Step 3: Concatenate with "ef": "abcabc" + "cdcdcd" + "ef" = "abcabccdcdcdef".
Constraints
  • 1 ≤ s.length ≤ 30
  • s consists of lowercase English letters, digits, and square brackets '[]'
  • s is guaranteed to be a valid input
  • Time Complexity: O(n)
  • Space Complexity: O(n)
StringsStackCapgeminiSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a stack-based approach to handle nested brackets.
  • Use two stacks: one for numbers and one for strings.
  • When you encounter '[', push current number and string to stacks.
  • When you encounter ']', pop from stacks and repeat the string.
  • Build the result string character by character.

Steps to solve by this approach:

 Step 1: Initialize two stacks - one for numbers and one for strings, along with a result string.
 Step 2: Iterate through each character in the input string.
 Step 3: If character is a digit, parse the complete number and push to number stack.
 Step 4: If character is '[', push current result to string stack and reset result.
 Step 5: If character is ']', pop number and string from stacks, repeat current result and concatenate.
 Step 6: If character is a regular letter, append it to the current result string.
 Step 7: Return the final result string after processing all characters.

Submitted Code :