-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
343 lines (290 loc) · 7.71 KB
/
main.cpp
File metadata and controls
343 lines (290 loc) · 7.71 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// Source: https://leetcode.com/problems/decode-string
// Title: Decode String
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given an encoded string, return its decoded string.
//
// The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer.
//
// You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`.
//
// The test cases are generated so that the length of the output will never exceed `10^5`.
//
// **Example 1:**
//
// ```
// Input: s = "3[a]2[bc]"
// Output: "aaabcbc"
// ```
//
// **Example 2:**
//
// ```
// Input: s = "3[a2[c]]"
// Output: "accaccacc"
// ```
//
// **Example 3:**
//
// ```
// Input: s = "2[abc]3[cd]ef"
// Output: "abcabccdcdcdef"
// ```
//
// **Constraints:**
//
// - `1 <= s.length <= 30`
// - `s` consists of lowercase English letters, digits, and square brackets `'[]'`.
// - `s` is guaranteed to be **a valid** input.
// - All the integers in `s` are in the range `[1, 300]`.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <cassert>
#include <cctype>
#include <charconv>
#include <cstddef>
#include <stack>
#include <string>
#include <string_view>
#include <vector>
using namespace std;
// Tokenizer
class Solution {
public:
string decodeString(string s) {
int n = s.size();
// Tokenize
auto tokens = stack<string>();
tokens.push("1"); // convert to 1[s]
for (int i = 0; i < n; ++i) {
// Parse string
if (isalpha(s[i])) {
int start = i;
for (; i < n && isalpha(s[i]); ++i);
tokens.push(s.substr(start, i - start));
--i;
continue;
}
// Parse number
if (isdigit(s[i])) {
int start = i;
for (; i < n && isdigit(s[i]); ++i);
tokens.push(s.substr(start, i - start));
--i;
continue;
}
// Parse bracket
if (s[i] == ']') tokens.push("]");
}
tokens.push("]"); // convert to 1[s]
// Decode
auto strs = stack<string>();
while (!tokens.empty()) {
string token = tokens.top();
tokens.pop();
// string
if (!isdigit(token[0])) {
strs.push(token);
continue;
}
// number
auto num = stoi(token);
// pop until ]
string str = "";
while (strs.top() != "]") {
str += strs.top();
strs.pop();
}
strs.pop();
// repeat
string repeated = "";
for (int i = 0; i < num; ++i) repeated += str;
strs.push(repeated);
}
return strs.top();
}
};
// Stack
//
// Store prefix number and string into the stack
class Solution2 {
public:
string decodeString(string s) {
auto st = stack<pair<int, string>>();
int currNum = 0;
string currStr = "";
for (char c : s) {
if (isdigit(c)) {
currNum = currNum * 10 + (c - '0');
continue;
}
if (isalpha(c)) {
currStr += c;
continue;
}
if (c == '[') {
st.emplace(currNum, currStr);
currNum = 0, currStr = "";
continue;
}
if (c == ']') {
auto [parentNum, parentStr] = st.top();
st.pop();
// Repeat
for (int i = 0; i < parentNum; ++i) parentStr += currStr;
swap(currStr, parentStr);
continue;
}
// won't reach here
}
return currStr;
}
};
// Tokenize + Parser + AST
//
// expr := str | repeat
// group := expr*
// repeat := num '[' group ']'
//
class Solution3 {
struct Token {
enum Type { NONE, STR, NUM, LBRACK, RBRACK };
Type type;
int start, end;
};
class Lexer {
public:
vector<Token> lex(const string_view s) const {
const int n = s.size();
auto tokens = vector<Token>();
Token token{Token::NONE, 0};
for (int i = 0; i <= n; ++i) {
char ch = s[i];
// Parse type
Token::Type type = Token::NONE;
bool forceNew = false;
if (i < n) {
if (isalpha(ch)) {
type = Token::STR;
} else if (isdigit(ch)) {
type = Token::NUM;
} else if (ch == '[') {
type = Token::LBRACK;
forceNew = true;
} else if (ch == ']') {
type = Token::RBRACK;
forceNew = true;
}
}
// Push token
if (type != token.type || forceNew) {
if (token.type != Token::NONE) {
token.end = i;
tokens.push_back(token);
}
token.type = type;
token.start = i;
}
}
return tokens;
}
};
struct Node {
virtual ~Node() = default;
virtual string decode(const string_view s) const = 0;
};
struct ExprNode : Node {};
struct StrNode : ExprNode {
int start, end;
StrNode(int start, int end) : start(start), end(end) {}
string decode(const string_view s) const override {
return string(s.substr(start, end - start)); //
}
};
struct NumNode : Node {
int num;
NumNode(const string_view s, int start, int end) {
from_chars(&s[start], &s[end], num); //
}
string decode(const string_view s) const override {
return ""; // num should not be decoded
}
};
struct GroupNode : Node {
vector<ExprNode*> children;
~GroupNode() {
for (auto node : children) {
delete node;
}
}
string decode(const string_view s) const override {
string out;
for (auto* child : children) out += child->decode(s);
return out;
}
};
struct RepeatNode : ExprNode {
NumNode* num;
GroupNode* body;
~RepeatNode() {
delete num;
delete body;
}
string decode(const string_view s) const override {
string out;
string sub = body->decode(s);
for (int i = 0; i < num->num; ++i) out += sub;
return out;
}
};
struct Parser {
public:
GroupNode* parse(const string_view s, vector<Token>& tokens) const {
int i = 0;
auto root = parseGroup(s, tokens, i);
assert(i == tokens.size());
return root;
}
private:
GroupNode* parseGroup(const string_view s, vector<Token>& tokens, int& i) const {
auto group = new GroupNode();
while (i < tokens.size() && tokens[i].type != Token::RBRACK) {
group->children.push_back(parseExpr(s, tokens, i));
}
return group;
}
ExprNode* parseExpr(const string_view s, vector<Token>& tokens, int& i) const {
assert(i < tokens.size());
if (tokens[i].type == Token::STR) {
auto node = new StrNode(tokens[i].start, tokens[i].end);
++i;
return node;
}
if (tokens[i].type == Token::NUM) {
auto repeat = new RepeatNode();
repeat->num = new NumNode(s, tokens[i].start, tokens[i].end);
++i;
assert(tokens[i].type == Token::LBRACK);
++i;
repeat->body = parseGroup(s, tokens, i);
assert(tokens[i].type == Token::RBRACK);
++i;
return repeat;
}
assert(false);
return nullptr;
}
};
Lexer lexer;
Parser parser;
public:
string decodeString(const string s) {
int n = s.size();
auto tokens = lexer.lex(s);
auto tree = parser.parse(s, tokens);
auto out = tree->decode(s);
delete tree;
return out;
}
};