-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
42 lines (38 loc) · 893 Bytes
/
Solution.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
#include <cctype>
#include <cstddef>
#include <string>
#include <string_view>
using namespace std;
class Solution {
private:
string decode(string_view s, int& i) {
// DFS
string result;
while (i < s.length() && s[i] != ']') {
if (isalpha(s[i])) {
result += s[i++];
continue;
}
// A digit indicates a nested string to be decoded.
int repeats = 0;
while (i < s.length() && isdigit(s[i])) {
repeats = (repeats * 10) + (s[i] - '0');
++i;
}
++i; // skip '[';
string flattened = decode(s, i);
++i; // skip ']'
while (repeats--) {
result += flattened;
}
}
return result;
}
public:
// Changing the signature to string_view is fine.
string decodeString(string_view s) {
// Seems similar to flattening a tree.
int i = 0;
return decode(s, i);
}
};