# Decode String Leetcode Solution

## Decode String Leetcode Problem :

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.

## Decode String Leetcode Solution :

### Constraints :

• The length of string is between 1 and 30.
• String consist of lowercase english letters, digits or square brackets[].
• S is guaranteed to be valid input.
• All the integers of the string are in the range between 1 and 300.

### Example 1:

Input: s = “3[a2[c]]”

Output: “accaccacc”

### Example 2:

Input:  s = “2[abc]3[cd]ef”

Output: “abcabccdcdcdef

## Explanation

1. If we see digit, it means that we need to form number, so just do it: multiply already formed number by `10` and add this digit.
2. If we see open bracket `[`, it means, that we just right before finished to form our number: so we put it into our stack. Also we put in our stack empty string.
3. If we have close bracket `]`, it means that we just finished `[...]` block and what we have in our stack: on the top it is solution for what we have inside bracktes, before we have number of repetitions of this string `rep` and finally, before we have string built previously: so we concatenate `str2` and `str1 * rep`.
4. Finally, if we have some other symbol, that is letter, we add it the the last element of our stack.

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others