leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0726.cpp (2753B)


0 class Solution {
1 enum Type {
2 Atom,
3 Number,
4 Extra,
5 };
7 public:
8 string countOfAtoms(const string &formula) const {
9 string res;
11 vector<string> tokens;
12 string crnt;
13 Type type = Extra;
15 for (const char c : formula) {
16 if (c == '(' || c == ')') {
17 tokens.push_back(crnt);
18 type = Extra;
19 crnt = "";
20 } else if (isdigit(c)) {
21 if (type != Number) {
22 tokens.push_back(crnt);
23 type = Number;
24 crnt = "";
25 }
26 } else {
27 if (type != Atom || isupper(c)) {
28 tokens.push_back(crnt);
29 type = Atom;
30 crnt = "";
31 }
32 }
34 crnt += c;
35 }
36 tokens.push_back(crnt);
38 using map_t = map<string, long long>;
40 map_t last_count;
41 stack<map_t> count;
42 string last_atom;
44 type = Extra;
45 count.push({});
46 tokens.erase(tokens.begin());
47 for (const auto &token : tokens) {
48 if (token[0] == '(') {
49 if (type == Atom) count.top()[last_atom]++;
50 count.push({});
51 type = Extra;
52 } else if (token[0] == ')') {
53 if (type == Atom) count.top()[last_atom]++;
54 last_count = std::move(count.top());
55 count.pop();
56 type = Extra;
57 } else {
58 if (isdigit(token[0])) {
59 const auto value = stoll(token);
60 if (type == Extra) {
61 for (auto &[_, v] : last_count)
62 v *= value;
63 } else {
64 count.top()[last_atom] += value;
65 }
66 }
68 if (type == Extra) {
69 for (const auto &[k, v] : last_count) {
70 count.top()[k] += v;
71 }
72 last_count = {};
73 }
75 if (isdigit(token[0]))
76 type = Number;
77 else {
78 if (type == Atom) count.top()[last_atom]++;
79 last_atom = token;
80 type = Atom;
81 }
82 }
83 }
85 if (type == Extra) {
86 for (const auto &[k, v] : last_count)
87 count.top()[k] += v;
88 } else if (type == Atom)
89 count.top()[last_atom]++;
91 for (const auto &[e, c] : count.top()) {
92 res += e;
93 if (c > 1) res += to_string(c);
94 }
96 return res;
97 }
98 };