Skip to content

Latest commit

 

History

History
89 lines (64 loc) · 3.7 KB

394.Decode_String(Medium).md

File metadata and controls

89 lines (64 loc) · 3.7 KB

394. Decode String (Medium)

Date and Time: Oct 17, 2024, 14:07 (EST)

Link: https://leetcode.com/problems/decode-string/


Question:

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 10^5.


Example 1:

Input: s = "3[a]2[bc]"

Output: "aaabcbc"

Example 2:

Input: s = "3[a2[c]]"

Output: "accaccacc"

Example 3:

Input: s = "2[abc]3[cd]ef"

Output: "abcabccdcdcdef"


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].


Walk-through:

Add each char from s into stack[] except i == "]". When we have "]", we first get the subStr by popping from the stack, then get the digits for how many times we need to repeat this subStr, and we append this repeated subStr into stack[] again, so when we have nested square brackets happen, we can repeat the subStr. Finall, concatenate all subStrs from stack[] and return.


Python Solution:

class Solution:
    def decodeString(self, s: str) -> str:
        # Convert everything in s into a string
        # Stack to store everything except "]"
        # "]": get the string we need to repeat and how many times
        # after we convert it into string, append to stack

        # TC: O(n^2), SC: O(n)
        stack = []
        for i in s:
            if i != "]":
                stack.append(i)
            else:
                # Get the string inside []
                subStr = ""
                while stack[-1] != '[':
                    subStr = stack.pop() + subStr
                stack.pop()     # Get rid of '['

                # Get how many times to repeat
                k = ""
                while stack and stack[-1].isdigit():
                    k = stack.pop() + k
                
                # Add repeated subStr into stack
                stack.append(int(k) * subStr) 

        # Concatenate all subStrs together
        return "".join(stack)

Time Complexity: $O(n^2)$
Space Complexity: $O(n)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms