-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecode String.cpp
More file actions
53 lines (50 loc) · 1.55 KB
/
Decode String.cpp
File metadata and controls
53 lines (50 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Runtime: 0 ms, faster than 100.00% of C++ online submissions for Decode String.
// Memory Usage: 7.1 MB, less than 15.17% of C++ online submissions for Decode String.
class Solution {
public:
string decodeString(string s) {
//have added comments to make the code self explanatory
int n = s.length();
string ans = "";
stack<int> stk1;
stack<string> stk2; //string that created till now
int i = 0;
while(i < n) {
if(s[i] == '[') {
stk2.push(ans);
ans = "";
i++;
}
else if(s[i] == ']') {
stk2.push(ans);
ans = "";
int times = stk1.top();
stk1.pop();
string tempstr = stk2.top();
stk2.pop();
for(int k = 0; k < times; k++) {
ans += tempstr;
}
if(!stk2.empty()) {
ans = stk2.top() + ans;
stk2.pop();
}
i++;
}
else if(s[i] - 'a' >= 0) {
ans += s[i];
i++;
}
else {
string count = "";
while(s[i] - 'a' <= -40){
count += s[i]; // if the number is greater that 10
i++;
}
int temp = stoi(count);
stk1.push(temp);
}
}
return ans;
}
};