![]() |
VOOZH | about |
Given an encoded string s, decode it by expanding the pattern k[substring], where the substring inside brackets is written k times. Return the final decoded string.
Examples:
Input: s = "3[b2[ca]]"
Output: bcacabcacabcaca
Explanation:
Inner substring "2[ca]" breakdown into "caca".
Now , new string becomes "3[bcaca]"
Similarly "3[bcaca]" becomes "bcacabcacabcaca" which is final result.Input: s = "3[ab]"
Output: ababab
Explanation: The substring "ab" is repeated 3 times, giving "ababab".
Table of Content
Use two stacks (one for numbers, one for characters). When ']' is found, pop till '[' to form a substring, repeat it using the top number, and push back β final stack gives the decoded string.
Illustration:
bcacabcacabcaca
In this approach, we use a single stack to store both characters and digits. Instead of maintaining a separate integer stack for storing repetition counts, we store the digits directly in the main stack. The key observation is that the number always appears before the opening bracket
'['. This allows us to retrieve it later without needing an extra stack.
']' is encountered.']' is found:'[' is found, then remove '['.bcacabcacabcaca
The approach is like traversing the encoded string character by character while maintaining a result string. Whenever a closing bracket ']' is found, we extract the substring enclosed within the matching opening bracket '[' and retrieve the number that indicates how many times the substring should be repeated. This repeated substring is then added back to the current result. By continuing this process until the end of the string, we obtain the fully decoded output.
bcacabcacabcaca