
Problem
Solution
Submissions
Decode String
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
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.
Example 1
- Input: s = "3[a]2[bc]"
- Output: "aaabcbc"
- Explanation:
- Process "3[a]" - repeat 'a' three times to get "aaa".
- Process "2[bc]" - repeat "bc" two times to get "bcbc".
- Concatenate results: "aaa" + "bcbc" = "aaabcbc".
- Final decoded string is "aaabcbc".
- Process "3[a]" - repeat 'a' three times to get "aaa".
Example 2
- Input: s = "2[a3[c]b]"
- Output: "accbaccb"
- Explanation:
- Start with innermost brackets "3[c]" - repeat 'c' three times to get "ccc".
- Replace in original: "2[acccb]". Process "2[acccb]" - repeat "acccb" two times.
- Final result: "acccb" + "acccb" = "accbaccb".
- Note: 'ccc' becomes 'cc' in each repetition due to the pattern "a3[c]b".
- Start with innermost brackets "3[c]" - repeat 'c' three times to get "ccc".
Constraints
- 1 ≤ s.length ≤ 30
- s consists of lowercase English letters, digits, and square brackets '[]'
- s is guaranteed to be a valid input
- All the integers in s are in the range [1, 300]
- Time Complexity: O(n) where n is the length of the decoded string
- Space Complexity: O(n) for the stack
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 to handle nested brackets and keep track of strings and their repetition counts
- Process the string character by character, building numbers and strings
- When encountering '[', push current string and number to stack
- When encountering ']', pop from stack and repeat the current string
- Handle nested structures by maintaining separate stacks for strings and numbers