C++ using stack not difficult


  • 0
    X
    class Solution {
    public:
        string countOfAtoms(string formula) {
            stack<map<string, int>> stk;
            stk.emplace();
            for (int i = 0; i < formula.size();) {
                if (formula[i] == '(') {
                    ++i;
                    stk.emplace();
                } else if (formula[i] == ')') {
                    ++i;
                    map<string, int> sub(std::move(stk.top())); stk.pop();
                    int num = 0;
                    while (isdigit(formula[i])) num = 10 * num + (formula[i++] - '0');
                    num = num ? num : 1;
                    for (auto &&atom : sub)
                        stk.top()[atom.first] += num * atom.second;
                } else {
                    string atom(1, formula[i++]);
                    while (islower(formula[i])) atom += formula[i++];
                    int num = 0;
                    while (isdigit(formula[i])) num = 10 * num + (formula[i++] - '0');
                    stk.top()[atom] += num ? num : 1;
                }
            }
    
            string ret;
            for (auto &&atom : stk.top()) {
                ret += atom.first;
                if (atom.second > 1) ret += to_string(atom.second);
            }
            return ret;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.