包括解析单个原子,以及解析数字,然后把原子和数字存到一起,map。
解析()可以用空格处理。代码如下:
typedef map<string, int> MPSI;
class Solution {
public:
string countOfAtoms(string formula) {
int i = 0, n = formula.size();
auto parseAtom = [&]() -> string {
string atom;
atom += formula[i++];
while (i < n && formula[i] >= 'a' && formula[i] <= 'z') {
atom += formula[i++];
}
return atom;
};
auto parseNum = [&]() -> int {
if (i == n || !isdigit(formula[i])) {
// 解析完atom之后没有数字,默认为1
// 注意最后实际上也有一个1
return 1;
}
int num = 0;
while (i < n && isdigit(formula[i])) {
num = num * 10 + (formula[i++] - '0');
}
return num;
};
function<MPSI(void)> dfs = [&]() -> MPSI{
MPSI res;
while (i < n) {
if (formula[i] == '(') {
i++;
MPSI t = dfs();
i++;
int cnt = parseNum();
for(auto &[x, y] : t) {
res[x] += cnt * y;
}
} else if (formula[i] == ')') {
return res;
} else {
string atom = parseAtom();
int num = parseNum();
res[atom] += num;
}
}
return res;
};
auto t = dfs();
string res;
for(auto &[x, y] : t) {
res += x;
if (y > 1) {
res += to_string(y);
}
}
return res;
}
};