- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 53 lines of C++ from the credited upstream file 726.cpp.
- The implementation visibly relies on ordered lookup.
- 6 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 string countOfAtoms(string formula) {4 string ans;5 int i = 0;6 7 for (const auto& [elem, freq] : parse(formula, i)) {8 ans += elem;9 if (freq > 1)10 ans += to_string(freq);11 }12 13 return ans;14 }15 16 private:17 map<string, int> parse(const string& s, int& i) {18 map<string, int> count;19 20 while (i < s.length())21 if (s[i] == '(') {22 for (const auto& [elem, freq] : parse(s, ++i))23 count[elem] += freq;24 } else if (s[i] == ')') {25 const int num = getNum(s, ++i);26 for (auto&& [_, freq] : count)27 freq *= num;28 return count; 29 } else { 30 const string& elem = getElem(s, i);31 const int num = getNum(s, i);32 count[elem] += num;33 }34 35 return count;36 }37 38 string getElem(const string& s, int& i) {39 const int elemStart = i++; 40 while (i < s.length() && islower(s[i]))41 ++i;42 return s.substr(elemStart, i - elemStart);43 }44 45 int getNum(const string& s, int& i) {46 const int numStart = i;47 while (i < s.length() && isdigit(s[i]))48 ++i;49 const string& numString = s.substr(numStart, i - numStart);50 return numString.empty() ? 1 : stoi(numString);51 }52};53