Leet Code Daily 2024-07-14 - Number of Atoms
Solution
Stack.
Code
class Formula {
public:
static shared_ptr<Formula> empty() { return make_shared<Formula>(); }
static shared_ptr<Formula> of(string name) {
auto ptr = make_shared<Formula>();
ptr->count[name] = 1;
return ptr;
}
string toString() {
string ret = "";
for (const auto& pair : this->count) {
ret.append(pair.first);
if (pair.second > 1) {
ret.append(to_string(pair.second));
}
}
return ret;
}
void add(const shared_ptr<Formula> other) {
for (const auto& pair : other->count) {
this->count[pair.first] += pair.second;
}
}
void times(int value) {
for (auto& pair : this->count) {
pair.second *= value;
}
}
private:
map<string, int> count;
};
class Solution {
public:
string countOfAtoms(string formula) {
formula = "(" + formula + ")";
stack<optional<shared_ptr<Formula>>> stack;
for (int i = 0; i < formula.size(); i++) {
if (formula[i] == '(') {
stack.push(nullopt);
continue;
}
if (formula[i] == ')') {
auto res = Formula::empty();
for (; stack.top().has_value(); stack.pop()) {
res->add(stack.top().value());
}
stack.top() = res;
continue;
}
if (isalpha(formula[i])) {
string name(1, formula[i]);
while (i + 1 < formula.size() && islower(formula[i + 1])) {
name.push_back(formula[++i]);
}
stack.push(Formula::of(name));
continue;
}
if (isdigit(formula[i])) {
int times = formula[i] - '0';
while (i + 1 < formula.size() && isdigit(formula[i + 1])) {
times = 10 * times + (formula[++i] - '0');
}
stack.top().value()->times(times);
}
}
return stack.top().value()->toString();
}
};