726. Number of Atoms
Input:
formula = "H2O"
Output: "H2O"
Explanation:
The count of elements are {'H': 2, 'O': 1}.Input:
formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation:
The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.Last updated
Input:
formula = "H2O"
Output: "H2O"
Explanation:
The count of elements are {'H': 2, 'O': 1}.Input:
formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation:
The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.Last updated
Input:
formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation:
The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.// Iteration
string countOfAtoms(string formula) { // time: O(n); space: O(n)
string res;
stack<map<string, int> > st;
map<string, int> cur;
int n = formula.length(), pos = 0;
while (pos < n) {
if (formula[pos] == '(') {
++pos; // skip '('
st.push(move(cur));
} else if (formula[pos] == ')') {
int i = ++pos; // skip ')'
// extract number
while (pos < n && isdigit(formula[pos])) ++pos;
int multiple = stoi(formula.substr(i, pos - i));
for (auto a : cur) {
map<string, int>& t = st.top();
t[a.first] += a.second * multiple;
}
cur = move(st.top());
st.pop();
} else {
int i = pos++;
// extract element
while (pos < n && islower(formula[pos])) ++pos;
string element = formula.substr(i, pos - i);
i = pos;
// extract number
while (pos < n && isdigit(formula[pos])) ++pos;
string cnt = formula.substr(i, pos - i);
cur[element] += (cnt.empty() ? 1 : stoi(cnt));
}
}
for (auto a : cur) {
res += a.first + (a.second == 1 ? "" : to_string(a.second));
}
return res;
}// Iteration
string countOfAtoms(string formula) { // time: O(n); space: O(n)
string res;
stack<map<string, int> > st;
map<string, int> cur;
int n = formula.length(), pos = 0;
while (pos < n) {
if (formula[pos] == '(') {
++pos; // skip '('
st.push(move(cur));
} else if (formula[pos] == ')') {
int i = ++pos; // skip ')'
// extract number
while (pos < n && isdigit(formula[pos])) ++pos;
int multiple = (pos == i) ? 1 : stoi(formula.substr(i, pos - i));
for (auto a : cur) {
map<string, int>& t = st.top();
t[a.first] += a.second * multiple;
}
cur = move(st.top());
st.pop();
} else {
int i = pos++; // i shouhd be the position of a uppercase char
// extract element
while (pos < n && islower(formula[pos])) ++pos;
string element = formula.substr(i, pos - i);
i = pos;
// extract number
while (pos < n && isdigit(formula[pos])) ++pos;
string cnt = formula.substr(i, pos - i);
cur[element] += (cnt.empty() ? 1 : stoi(cnt));
}
}
for (auto a : cur) {
res += a.first + (a.second == 1 ? "" : to_string(a.second));
}
return res;
}