forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
// 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 }; | ||
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;) { | ||
auto name = (it++)->str(); | ||
auto m1 = (it++)->str(); | ||
auto left_open = (it++)->str(); | ||
auto right_open = (it++)->str(); | ||
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; | ||
} | ||
}; |