LeetCode 394. Decode String

2026. 1. 7. 21:34·코딩테스트/LeetCode

394. Decode String

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.



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

 


 

Solution

The key requirements of this problem are as follows:

  1. Value of s is made of the k[string] format.
  2. Decode the string by multiplying string k times.
  3. Return final decoded string.

To satisfy this requirements, I used a stack approach with multiple lists.

The elements of s are digits, characters and brackets.

 

First, while iterating though the string, append each element to the result list as long as the element is not a closing bracket.

 

ex)
s = "21[abc]3[cd]ef"
result = ["2", "1", "[", "a" , "b", "c"]

 

Next, when a closing bracket is encountered, move characters from result to the chars list while result[-1] != "[", and pop each character from result.

 

 

ex)
s = "21[abc]3[cd]ef"
result = ["2", "1", "["]
chars = ["c", "b", "a"]

 

 

Since the stack stores elements in reverse order, reverse chars to restore the correct order.

 

Afther that, pop the opening bracket.

Then, while result is not empty and result[-1].isdigit() is true, build the digit string using str_num = result.pop() + str_num.

 

The reason why adding digits this way is that stack pops elements in reverse order.


For example, 21 is stored as "2" then "1", so "1" is popped first.

 

ex)
s = "21[abc]3[cd]ef"
result = []
chars = ["a", "b", "c"]
str_num = '21'

 

 

Convert str_num into an integer and multiply the decoded string.

Using ''.join(chars) * num , the string "abc" is repeated 21 times and appended to result.

 

 

ex)
result = ["abc", "abc"...]

 

 

After finishing the iteration, return the final decoded string.

 

 

class Solution(object):
    def decodeString(self, s):
        result = []
        for i in s:
            if i != "]":
                result.append(i)
            else:
                char = []
                while result[-1] != "[":
                    char.append(result.pop())
                char.reverse()
                result.pop()

                str_num = ''
                while result and result[-1].isdigit():
                    str_num = result.pop() + str_num

                num = int(str_num)if str_num else 1
                temp = ''.join(char) * num
                for i in temp:
                    result.append(i)

        return ''.join(result)

https://github.com/K-MarkLee/LeetCode-Practice

 

GitHub - K-MarkLee/LeetCode-Practice: A collection of LeetCode questions to ace the coding interview! - Created using [LeetHub 2

A collection of LeetCode questions to ace the coding interview! - Created using [LeetHub 2.0](https://github.com/maitreya2954/LeetHub-2.0-Firefox) - K-MarkLee/LeetCode-Practice

github.com

 

저작자표시 비영리 변경금지 (새창열림)

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode 649. Dota2 Senate  (0) 2026.01.10
LeetCode 933. Number of Recent Calls  (0) 2026.01.09
LeetCode 2352. Equal Row and Column Pairs  (0) 2026.01.05
LeetCode 1657. Determine if Two Strings Are Close  (0) 2026.01.05
LeetCode 1207. Unique Number of Occurrences  (0) 2026.01.03
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode 649. Dota2 Senate
  • LeetCode 933. Number of Recent Calls
  • LeetCode 2352. Equal Row and Column Pairs
  • LeetCode 1657. Determine if Two Strings Are Close
코드 유랑자 승열
코드 유랑자 승열
코드 유랑자 승열의 프로그래밍 일지를 남기는 공간입니다.
  • 코드 유랑자 승열
    승열의 프로그래밍 시네마
    코드 유랑자 승열
  • 전체
    오늘
    어제
  • 링크

    • 깃허브 보러가기
    • 링크드인 보러가기
    • 카테고리
      • 코딩테스트
        • LeetCode
        • BaekJoon
      • TIL and WIL
        • TIL
        • WIL
      • 주말스터디
      • 내일배움캠프
        • 사전캠프 강의 (SQL)
      • 용어정리
        • Python
        • Python-Library
        • Machine-Learning
        • Deep-Learning
        • AI 활용
        • LLM & RAG
        • Docker
        • Django
        • SQL
        • Java Script
        • etc
      • Daily 코드카타
        • SQL
        • Python 알고리즘
      • 임시저장
      • 보류
  • 태그

    django
    RAG
    template
    View
    티스토리챌린지
    llm
    오블완
    langchain
    vector db
    word2vec
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
코드 유랑자 승열
LeetCode 394. Decode String
상단으로

티스토리툴바