
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".
- Step 1: "3[a]" means repeat "a" 3 times, resulting in "aaa".
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".
- Step 1: "2[abc]" means repeat "abc" 2 times, resulting in "abcabc".
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)
Editorial
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. |
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.