-
Notifications
You must be signed in to change notification settings - Fork 7
/
StringDecoder.cpp
56 lines (52 loc) · 1.57 KB
/
StringDecoder.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
// Problem-Link: https://leetcode.com/problems/decode-string/
#include<string>
#include<stack>
using namespace std;
class StringDecoder {
public:
string decodeString(string s) {
string output = "";
for (int i = 0; i < s.size(); ++i) {
char curr_ch = s.at(i);
// Pushing to a stack.
if (curr_ch == '"') continue;
// Removing from the stack.
if (curr_ch == ']') {
string s_rep;
// Finding s_rep.
while (elems.size() > 0) {
char in_ch = elems.top();
elems.pop();
if (in_ch == '[') break;
s_rep.insert(s_rep.begin(), in_ch);
}
string num_rep_str;
while (elems.size() > 0) {
char in_ch = elems.top();
if (std::isdigit(in_ch)) {
num_rep_str.insert(num_rep_str.begin(), in_ch);
elems.pop();
} else {
break;
}
}
int num_rep = std::stoi(num_rep_str);
// Adding s_rep to output.
for (int i = 0; i < num_rep; ++i){
for (int j = 0; j < s_rep.size(); ++j){
elems.push(s_rep.at(j));
}
}
continue;
}
elems.push(curr_ch);
}
while (elems.size() > 0){
output.insert(output.begin(), elems.top());
elems.pop();
}
return output;
}
private:
stack<char> elems;
};