Статья пока доступна только на английском.
Problem Description
You are given an encoded string; return its decoded version.
The encoding rule is k[encoded_string], meaning the string inside the square brackets
must be repeated exactly k times.
Note that k is guaranteed to be a positive integer.
The input string is always guaranteed to be valid: there are no extra spaces and the square brackets are well-formed.
Furthermore, the digits in the string are only used for the repeat numbers k.
For example, there won't be input like 3a or 2[4].
Note that encoded strings can be nested inside each other.
Constraints
- The input string length is in the range from 1 to 30
- The input string consists only of lowercase English letters, digits and square brackets
- The input string is always valid
kis in the range from 1 to 300- The length of the resulting string does not exceed 105
Examples
Input: "3[a]2[bc]"
Answer: "aaabcbc"
Solution
This problem can be solved recursively with the following algorithm.
- Create an empty result string that accumulates the decoded output.
- Iterate over the string character by character and check the following:
- If the current character is a letter (from 'a' to 'z'), append it to the result
resand move on to the next character. - If it's a digit, it marks the start of an encoded block.
The number before
[(the repeat count) is read character by character. Sincekcan have several digits, we accumulatecountin a loop, adding each new digit while taking its position into account (multiplying by 10).
- If the current character is a letter (from 'a' to 'z'), append it to the result
- After reading
countand finding the opening bracket[, the algorithm looks for the matching closing bracket]. This is done with a counterbracket, which is incremented on[and decremented on], so nested brackets are handled correctly. - Once the matching closing bracket is found, we cut out the substring between
[and]and calldecodeStringon it recursively. The result of that call is repeatedcounttimes and appended to the overall resultres. - The index
iis moved to the position of the closing bracket to continue traversing the string after the processed block.
export const decodeString = (s: string): string => {
let res = '';
for (let i = 0; i < s.length; i++) {
if (s[i] >= 'a' && s[i] <= 'z') {
res += s[i];
continue;
}
let count = 0;
while (s[i] != '[') {
count = count * 10 + Number(s[i]);
i++;
}
let bracket = 1;
let j = i + 1;
while (bracket > 0) {
if (s[j] == '[') {
bracket++;
}
if (s[j] == ']') {
bracket--;
}
j++;
}
res += decodeString(s.substring(i + 1, j - 1)).repeat(count);
i = j - 1;
}
return res;
};Complexity Analysis
Time Complexity
The complexity is O(maxk * n), where maxk is the maximum value of k and n is the length of the string s.
Space Complexity
O(n): the space used by the call stack for the recursion.
Since we decode each nested pattern recursively, the maximum depth of the recursion stack does not exceed n.