递归+map自动升序
因为有括号的存在,分解为小问题处理
class Solution {
private:
map<string, int> cnt;
public:
void count(string s, int t) {
//cout << s << endl;
if(s == "") return ;
if(s.find('(') == s.npos) { //无括号
string word = "";
for(int i = 0; i < s.size(); i++) {
if(isupper(s[i])) {
if(word != "") cnt[word] += t;
word = "";
word += s[i];
}
else if(islower(s[i])) {
word += s[i];
}
else {
string x = "";
while(i < s.size() && isdigit(s[i])) {
x += s[i];
i++;
}
i--;
if(x != "") cnt[word] += t * stoi(x);
word = "";
}
}
if(word != "") cnt[word] += t;
}
else {
string tmp = "";
int flag = 0;
for(int i = 0; i < s.size(); i++) {
if(flag == 0 && s[i] != '(') tmp += s[i];
else if(flag == 0 && s[i] == '(') {
count(tmp, t);
tmp = "";
flag = 1;
}
else if(flag > 0) {
if(s[i] == '(') {
tmp += s[i];
flag++;
}
else if(s[i] == ')') {
flag--;
if(flag == 0) { //括号结束,统计次数
i++;
string x = "";
while(i < s.size() && isdigit(s[i])) {
x += s[i];
i++;
}
i--;
if(x != "") count(tmp, t * stoi(x));
else count(tmp, t);
tmp = "";
}
else tmp += s[i];
}
else tmp += s[i];
}
}
if(tmp != "") count(tmp, t);
}
}
string countOfAtoms(string formula) {
count(formula, 1);
string ans = "";
for(auto [s, t] : cnt) {
ans += s;
if(t > 1) ans += to_string(t);
}
return ans;
}
};