394. Decode String
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; 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 won’t be input like 3a
or 2[4]
.
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"
To solve this problem, we need to deal with nested structures and repetitions. We can use a stack-based approach to handle this efficiently.
[
, push the current number and the current result string onto their respective stacks, then reset them.]
, pop from both stacks and construct the repeated string, then concatenate it to the previous result string.result
string will contain the fully decoded string.For s = "3[a2[c]]"
:
3
: counts = [3], result = “”[
: counts = [3], strings = [””], result = “”a
: result = “a”2
: counts = [3, 2], result = “a”[
: counts = [3, 2], strings = [””, “a”], result = “”c
: result = “c”]
: pop 2 and “a”, result = “acc”]
: pop 3 and “”, result = “accaccacc”#include <iostream>
#include <stack>
#include <string>
using namespace std;
class Solution {
public:
string decodeString(string s) {
stack<int> counts;
stack<string> strings;
string result;
int idx = 0;
while (idx < s.size()) {
if (isdigit(s[idx])) {
int count = 0;
while (isdigit(s[idx])) {
count = count * 10 + (s[idx] - '0');
idx++;
}
counts.push(count);
} else if (s[idx] == '[') {
strings.push(result);
result = "";
idx++;
} else if (s[idx] == ']') {
string temp = result;
result = strings.top();
strings.pop();
int count = counts.top();
counts.pop();
while (count > 0) {
result += temp;
count--;
}
idx++;
} else {
result += s[idx];
idx++;
}
}
return result;
}
};
// Example usage:
int main() {
Solution solution;
string s = "3[a2[c]]";
cout << "Decoded String: " << solution.decodeString(s) << endl; // Output: "accaccacc"
return 0;
}
The time complexity of this solution is O(n), where n
is the length of the input string. We process each character of the input string exactly once, and the operations performed in each step (push, pop, and concatenate) are efficient. The space complexity is also O(n) due to the additional stacks used to store counts and substrings.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?