Problem Statement:
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.
Examples:
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].
Time Complexity:
Time Complexity = O(n x k)
where n is length of string and k is max repetition.
Space Complexity:
Space Complexity = O(n)
Approach
- Use recursion to handle nested patterns like
k[encoded_string]. - Maintain a global pointer (
i) to traverse the string. - For each character:
- If it is a digit, build the number
k(to handle multi-digit values). - If you encounter
"[", recursively decode the substring inside the brackets. - Repeat the decoded substring
ktimes and append it to the result. - If you encounter
"]", return the current built string (end of current recursion level). - If it is a character, directly append it to the
result.
- If it is a digit, build the number
Dry Run
Input: s = "3[a2[c]]"
Initial:
i = 0
Call decode():
res = ""
num = 0
i = 0 → char = '3'
num = 3
i = 1
i = 1 → char = '['
i = 2
Call decode():
res = ""
num = 0
i = 2 → char = 'a'
res = "a"
i = 3
i = 3 → char = '2'
num = 2
i = 4
i = 4 → char = '['
i = 5
Call decode():
res = ""
num = 0
i = 5 → char = 'c'
res = "c"
i = 6
i = 6 → char = ']'
i = 7
return "c"
Back to previous call:
str = "c"
res = "a" + "c".repeat(2) = "acc"
num = 0
i = 7 → char = ']'
i = 8
return "acc"
Back to main call:
str = "acc"
res = "" + "acc".repeat(3) = "accaccacc"
num = 0
i = 8 → end of string
Final:
return "accaccacc"
Output: "accaccacc"
var decodeString = function(s) {
let i = 0;
let decode = () => {
let res = "";
let num = 0;
while (i < s.length) {
let char = s[i];
if (char >= '0' && char <= '9') {
num = num * 10 + parseInt(char);
i++;
}
else if (char === "[") {
i++;
let str = decode();
res += str.repeat(num);
num = 0;
}
else if (char === "]") {
i++;
return res;
}
else {
res += char;
i++;
}
}
return res;
};
return decode();
};
def decodeString(s: str) -> str:
i = 0
def decode():
nonlocal i
res = ""
num = 0
while i < len(s):
char = s[i]
if char.isdigit():
num = num * 10 + int(char)
i += 1
elif char == '[':
i += 1
decoded = decode()
res += decoded * num
num = 0
elif char == ']':
i += 1
return res
else:
res += char
i += 1
return res
return decode()
class Solution {
int i = 0;
public String decodeString(String s) {
return decode(s);
}
private String decode(String s) {
StringBuilder res = new StringBuilder();
int num = 0;
while (i < s.length()) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
num = num * 10 + (ch - '0');
i++;
}
else if (ch == '[') {
i++;
String decoded = decode(s);
for (int k = 0; k < num; k++) {
res.append(decoded);
}
num = 0;
}
else if (ch == ']') {
i++;
return res.toString();
}
else {
res.append(ch);
i++;
}
}
return res.toString();
}
}
class Solution {
public:
int i = 0;
string decodeString(string s) {
return decode(s);
}
string decode(string &s) {
string res = "";
int num = 0;
while (i < s.length()) {
char ch = s[i];
if (isdigit(ch)) {
num = num * 10 + (ch - '0');
i++;
}
else if (ch == '[') {
i++;
string decoded = decode(s);
while (num--) res += decoded;
num = 0;
}
else if (ch == ']') {
i++;
return res;
}
else {
res += ch;
i++;
}
}
return res;
}
};
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char* decode(char* s, int* i);
char* decodeString(char* s) {
int i = 0;
return decode(s, &i);
}
char* decode(char* s, int* i) {
char* res = (char*)malloc(10000); // assume max size
res[0] = '\0';
int num = 0;
while (s[*i] != '\0') {
char ch = s[*i];
if (isdigit(ch)) {
num = num * 10 + (ch - '0');
(*i)++;
}
else if (ch == '[') {
(*i)++;
char* decoded = decode(s, i);
for (int k = 0; k < num; k++) {
strcat(res, decoded);
}
num = 0;
free(decoded);
}
else if (ch == ']') {
(*i)++;
return res;
}
else {
int len = strlen(res);
res[len] = ch;
res[len + 1] = '\0';
(*i)++;
}
}
return res;
}
public class Solution {
int i = 0;
public string DecodeString(string s) {
return Decode(s);
}
private string Decode(string s) {
string res = "";
int num = 0;
while (i < s.Length) {
char ch = s[i];
if (char.IsDigit(ch)) {
num = num * 10 + (ch - '0');
i++;
}
else if (ch == '[') {
i++;
string decoded = Decode(s);
for (int k = 0; k < num; k++) {
res += decoded;
}
num = 0;
}
else if (ch == ']') {
i++;
return res;
}
else {
res += ch;
i++;
}
}
return res;
}
}
