1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
number-of-atoms.cpp 1.32 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 8年前 . Update number-of-atoms.cpp
// Time: O(n)
// Space: O(n)
class Solution {
public:
string countOfAtoms(string formula) {
stack<map<string, int>> stk;
stk.emplace();
int submatches[] = { 1, 2, 3, 4, 5 };
const auto e = regex("([A-Z][a-z]*)(\\d*)|(\\()|(\\))(\\d*)");
for (regex_token_iterator<string::iterator> it(formula.begin(), formula.end(), e, submatches), end;
it != end;) {
const auto& name = (it++)->str();
const auto& m1 = (it++)->str();
const auto& left_open = (it++)->str();
const auto& right_open = (it++)->str();
const auto& m2 = (it++)->str();
if (!name.empty()) {
stk.top()[name] += stoi(!m1.empty() ? m1 : "1");
}
if (!left_open.empty()) {
stk.emplace();
}
if (!right_open.empty()) {
const auto top = move(stk.top()); stk.pop();
for (const auto& kvp: top) {
stk.top()[kvp.first] += kvp.second * stoi(!m2.empty() ? m2 : "1");
}
}
}
string result;
for (const auto& kvp : stk.top()) {
result += kvp.first;
if (kvp.second > 1) {
result += to_string(kvp.second);
}
}
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助