-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecodeString.cpp
More file actions
51 lines (51 loc) · 1.43 KB
/
DecodeString.cpp
File metadata and controls
51 lines (51 loc) · 1.43 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
class Solution {
public:
string decodeString(string s) {
int i = 0;
stack<string> st;
st.push(string());
while (i < s.size()) {
string next = parseNext(s, i);
if (isdigit(next[0])) {
// Push the number to repeat
st.push(next);
// Parse the '[' and push an empty string
parseNext(s, i);
st.push(string());
} else if (next == "]") {
// Pop off string to repeat
string repeat = st.top();
st.pop();
// Pop off the number to repeat
int n = stoi(st.top());
st.pop();
for (int j = 0; j < n; ++j) {
st.top().append(repeat);
}
} else {
st.top().append(next);
}
}
return st.top();
}
private:
// Parse '[', ']', consecutive digits/letters
string parseNext(string& s, int& i) {
if (!isalnum(s[i])) {
return string(1, s[i++]);
}
string next;
if (isdigit(s[i])) {
while (i < s.size() && isdigit(s[i])) {
next.push_back(s[i]);
++i;
}
} else {
while (i < s.size() && isalpha(s[i])) {
next.push_back(s[i]);
++i;
}
}
return next;
}
};