Leetcode 394: Decode String

grid47
grid47
Exploring patterns and algorithms
Sep 28, 2024 6 min read

A string decoding into a sequence, with each decoded character softly illuminated.
Solution to LeetCode 394: Decode String Problem

You are given a string that is encoded using the pattern k[encoded_string], where the substring inside the square brackets is repeated exactly k times. Your task is to decode the string by expanding it according to the given encoding rule.
Problem
Approach
Steps
Complexity
Input: The input is a string encoded using the pattern k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times.
Example: Input: 2[ab]3[c]
Constraints:
• 1 <= s.length <= 30
• s consists of lowercase English letters, digits, and square brackets '[]'.
• All integers in s are in the range [1, 300].
Output: The output is a string representing the decoded version of the input encoded string.
Example: Output: ababc
Constraints:
• The decoded string must follow the encoding rule exactly.
Goal: The goal is to decode the given string by expanding the encoded substrings based on the provided encoding pattern.
Steps:
• Iterate over the input string character by character.
• When encountering a digit, parse the full number to determine how many times to repeat the enclosed substring.
• Recursively process the substring inside the brackets, and concatenate it according to the repetition count.
• Repeat the process until the entire string has been decoded.
Goal: The solution should handle decoding efficiently within the given input size and constraints.
Steps:
• The solution must work for input strings with lengths up to 30 characters.
Assumptions:
• The input string is always valid and well-formed.
Input: Input: 2[ab]3[c]
Explanation: The pattern '2[ab]' means 'ab' is repeated 2 times to form 'abab', and '3[c]' means 'c' is repeated 3 times to form 'ccc'. Combining these gives the final output 'ababccc'.

Input: Input: 2[a2[b]]
Explanation: First, decode 'a2[b]' where 'b' is repeated 2 times to form 'bb', so 'a2[b]' becomes 'abb'. Repeating this 2 times gives 'abbabb'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus