Approach
Initialization: Two stacks, nums and st, are used to keep track of numbers (repeat counts) and partially built strings, respectively. An integer num is initialized to 0 to build up numbers in the input string, and a string ans is initialized to empty, which will hold the currently processed output.
Loop Through the String: The code iterates over each character in the input string s.
Handling Digits: If the current character is a digit (isdigit(s[i])), it updates num to include this digit. This is done by multiplying num by 10 (to shift its value one decimal place to the left) and adding the numeric value of the current character. This process constructs the multiplier for the upcoming bracketed substring.
Handling Letters: If the current character is a letter (isalpha(s[i])), it appends the character to ans, building up the string to be eventually returned or used in a decoded section.
Opening Bracket [: When an opening bracket is encountered, it means a new section of encoded string is starting. The code pushes the current ans string and the current num value onto their respective stacks. This action saves the current state before processing the bracketed section. It then resets ans and num to start fresh for the new section.
Closing Bracket ]: Upon finding a closing bracket, the code retrieves the most recent number (prev_num) and string (prev_st) from the stacks nums and st, respectively. It then appends the current ans string to prev_st prev_num times, effectively decoding the current bracketed section. The result is stored back in ans, now updated with the expanded substring.
Return Result: After processing the entire string, the method returns ans, which now contains the fully decoded string.
Example Walkthrough:
If s = "3[a2[bc]]", the method works as follows:
Processes 3, setting num = 3.
Encounters [, saves the current state (empty string and 3), and resets.
Processes a, appending it to ans.
Processes 2, setting num = 2.
Encounters [, saves the current state (a and 2), and resets.
Processes bc, appending it to ans.
Encounters ], pops 2 and a from the stacks, repeats bc 2 times appending to a, resulting in abcbc.
Encounters another ], pops 3 and the empty string, repeats abcbc 3 times.
The final result, abcbcabcbcabcbc, is returned.Time complexity: O(n)
Space complexity:
best case O(d)
worst-case space complexity of O(n + d)
where n is the length of the input string and d is the depth of the bracket nesting.
class Solution {
public:
string decodeString(string s) {
stack<int>nums;
stack<string>st;
int num = 0;
string ans ="";
for(int i =0 ; i<s.size();i++){
if(isdigit(s[i])){
num = num * 10 + ( s[i] - '0');
}
else if (isalpha(s[i])){
ans += s[i];
}
else if(s[i] == '['){
st.push(ans);
nums.push(num);
ans = "";
num = 0;
}
else if( s[i] == ']'){
int prev_num = nums.top();
nums.pop();
string prev_st = st.top();
st.pop();
for(int j =0 ;j< prev_num ; j++){
prev_st += ans;
}
ans = prev_st;
}
}
return ans;
}};