Number of Atoms

 

CREATED TIME: Feb 20, 2020 2:26 AM UPDATED TIME: Feb 20, 2020 2:26 AM 난이도: hard

class Solution { public: string countOfAtoms(string formula) { stack<map<string, int» map_stack; map<string, int> first;

        map_stack.push(first);
        
        int i = 0;
        while(i < formula.length()){
            if(formula[i] == '('){
                map_stack.push(map<string, int>());
                i++;
            }else if(formula[i] == ')'){
                map<string, int> hm = map_stack.top();
                map_stack.pop();
                
                i++; 
                int orig_i = i;
                
                while(i < formula.length() && isdigit(formula[i])) i += 1;
                
                int hm_count_int = 1;
                string hm_count = formula.substr(orig_i, i - orig_i + 1);
                hm_count_int = stoi(hm_count);
                
                for(auto it:hm){
                    map_stack.top()[it.first] += it.second * hm_count_int;
                }
                
            }else{
                map<string, int> hm = map_stack.top();
                int orig_i = i;
                i += 1;
                while(i < formula.length() && islower(formula[i])) i += 1;
                
                string hm_key = formula.substr(orig_i, i - orig_i);
                
                
                
                orig_i = i;
                int hm_count_int = 1;
                
                if (isdigit(formula[i])){
                    while(i < formula.length() && isdigit(formula[i])) i += 1;
                
                    string hm_count = formula.substr(orig_i, i - orig_i + 1);
                    hm_count_int = stoi(hm_count);
                }
            
                map_stack.top()[hm_key] += hm_count_int;
            }
        }
        
        string ans;
        for (auto p:map_stack.top()) {
            ans += p.first;
            if (p.second > 1) ans += to_string(p.second);
        }
        
        
        return ans;
    }
};