-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDecodeString_394.cpp
65 lines (55 loc) · 1.71 KB
/
DecodeString_394.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 394. Decode String
~ Link : https://leetcode.com/problems/decode-string/
*/
class Solution {
public:
string decodeString(string s) {
string res = "";
stack<char> stk;
vector<pair<string, int> > group;
for (int i = 0; i < s.size(); ++i) {
if (s[i] >= '0' && s[i] <= '9') {
string freq = "";
while (i < s.size()) {
if (!(s[i] >= '0' && s[i] <= '9')) {
--i;
break;
}
freq.push_back(s[i++]);
}
group.push_back({"", stoi(freq)});
}
else if (s[i] == '[') {
stk.push(s[i]);
}
else if (s[i] == ']') {
stk.pop();
string curr = group.back().first;
int currFreq = group.back().second;
group.pop_back();
if (stk.empty()) {
while (currFreq--) {
res += curr;
}
}
else {
while (currFreq--) {
group.back().first += curr;
}
}
}
else if (s[i] >= 'a' && s[i] <= 'z') {
if (stk.empty())
res.push_back(s[i]);
else {
group.back().first.push_back(s[i]);
}
}
}
return res;
}
};
// Time Complexity - O(n^2 * 300)
// Auxiliary Space - O(n * 300)