-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode-string.cpp
79 lines (66 loc) · 1.88 KB
/
decode-string.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* Copyright (c) 2021, Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
// clang-format off
// name: decode-string
// url: https://leetcode.com/problems/decode-string
// difficulty: 2
// clang-format on
#include <vector>
using namespace std;
class Solution {
public:
string decodeString(string s) {
// maintain stacks (lifo queues) for both lefts and rights
// it takes O(N) time to go through s and populate them
// possible optimization:
// technically speaking, there can be maximally N/4 lefts and N/4 rights
// so maybe it just makes sense to preallocate that amount and keep
// an L and R handy.
// the question says that s will be maximally 30 characters.
// so that would allow us to be O(1) space (except for the output
// which is proportional in length to the input, so O(N)).
stringstream ss;
vector<size_t> nums;
uint8_t lefts = 0;
vector<string> strs;
string num;
bool have_number = false;
for (size_t i = 0, N = s.size(); i < N; ++i) {
if ('[' == s[i]) {
// we can now parse the number string that precedes the '[' character
nums.push_back(stoi(num));
num.clear();
++lefts;
strs.push_back("");
} else if (']' == s[i]) {
auto j = nums.back();
string t = strs.back();
nums.pop_back();
lefts--;
strs.pop_back();
if (nums.size() > 0) {
for (; j > 0; --j) {
strs.back() += t;
}
} else {
for (; j > 0; --j) {
ss << t;
}
}
} else if ('0' <= s[i] && s[i] <= '9') {
have_number = true;
num.push_back(s[i]);
} else if ('a' <= s[i] && s[i] <= 'z') {
if (!have_number || lefts == 0) {
ss << s[i];
} else {
strs.back().push_back(s[i]);
}
}
}
return ss.str();
}
};