[LeetCode] Number of Atoms

726. Number of Atoms

Given a string formula representing a chemical formula, return the count of each atom.

The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.

One or more digits representing that element’s count may follow if the count is greater than 1. If the count is 1, no digits will follow.

  • For example, “H2O” and “H2O2” are possible, but “H1O2” is impossible.

Two formulas are concatenated together to produce another formula.

  • For example, “H2O2He3Mg4” is also a formula.

A formula placed in parentheses, and a count (optionally added) is also a formula.

  • For example, “(H2O2)” and “(H2O2)3” are formulas.

Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.

The test cases are generated so that all the values in the output fit in a 32-bit integer.

  • Time : O(n + klogk)
  • Space : O(k)
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
class Solution {
bool isLowercase(char ch) {
return ('a' <= ch and ch <= 'z');
}

bool isUppercase(char ch) {
return 'A' <= ch and ch <= 'Z';
}

string serializeAtom(string formula, int &i) {
stringstream ss;
while(i < formula.length() and isLowercase(formula[i])) {
ss<<formula[i++];
}
return ss.str();
}

int serializeCnt(string formula, int &i) {
int res = 0;
while(i < formula.length() and isdigit(formula[i])) {
res = res * 10 + (formula[i++] & 0b1111);
}
return res;
}

unordered_map<string, int> serialize(string formula, int &i) {
unordered_map<string, int> res;
while(i < formula.length() and formula[i] != ')') {
if(isUppercase(formula[i])) {
string atom = formula[i] + serializeAtom(formula, ++i);
int count = i < formula.length() and isdigit(formula[i]) ? serializeCnt(formula, i) : 1;
res[atom] += count;
} else if(formula[i] == '(') {
unordered_map<string, int> innerResult = serialize(formula, ++i);
int multiply = i < formula.length() and isdigit(formula[i]) ? serializeCnt(formula, i) : 1;
for(auto [atom, count] : innerResult) {
res[atom] += count * multiply;
}
}
}
i++;
return res;
}
public:
string countOfAtoms(string formula) {
int i = 0;
unordered_map<string, int> atoms = serialize(formula, i);
map<string, int> sortedAtom(atoms.begin(), atoms.end());
stringstream ss;
for(auto [atom, count]: sortedAtom) {
ss<<atom;
if(count > 1) ss<<to_string(count);
}
return ss.str();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/14/PS/LeetCode/number-of-atoms/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.