I was trying this problem on leetcode https://leetcode.com/problems/decode-string/
I came across this particular solution. Code is below.
class Solution {
public:
string decodeString(string s) {
stack<string> chars;
stack<int> nums;
string res;
int num = 0;
for(char c : s) {
if(isdigit(c)) {
num = num*10 + (c-'0');
}
else if(isalpha(c)) {
res.push_back(c);
}
else if(c == '[') {
chars.push(res);
nums.push(num);
res = "";
num = 0;
}
else if(c == ']') {
string tmp = res;
for(int i = 0; i < nums.top()-1; ++i) {
res += tmp;
}
res = chars.top() + res;
chars.pop(); nums.pop();
}
}
return res;
}
};
Isn't the time complexity of this solution dependent on the numbers that are present in the string? As we are adding a string that many times. Also I feel if there will be some kind of multiplication going on. For example
For input : 3[ab4[c]]
In a very crude way won't the complexity be something like 3*(len(ab) + 4*(len(c)). Am I correct?
