My C++ solution


  • 0
    class Solution {
    public:
    	string countOfAtoms(string formula) {
    		auto t = ForParent(formula);
    		string temp;
    		for (auto x : t) {
    			temp += x.first;
    			if (x.second != 1)
    				temp += std::to_string(x.second);
    		}
    		return temp;
    	}
    	inline void insert_into_map(map<string, int>& map, string temp, int t) {
    		if (map.find(temp) != map.end())
    			map[temp] += t;
    		else
    			map[temp] = t;
    	}
    	map<string, int> ForParent(string str) {
    		map<string, int> map_result;
    		int i = 0;
    		string temp;
    		int int_temp = 0;
    		while (i < str.size()) {
    			if (str[i] >= 'a'&&str[i] <= 'z') {
    				temp += str[i];
    			}
    			else if (str[i] >= '0'&&str[i] <= '9') {
    				while (str[i] >= '0'&&str[i] <= '9') {
    					int_temp = int_temp * 10 + str[i] - '0';
    					i++;
    				}
    				i--;
    				insert_into_map(map_result, temp, int_temp);
    				temp.clear();
    				int_temp = 0;
    			}
    			else if (str[i] >= 'A'&&str[i] <= 'Z') {
    				if (!temp.empty()) {
    					if (int_temp == 0) int_temp = 1;
    					insert_into_map(map_result, temp, int_temp);
    					temp.clear();
    					int_temp = 0;
    				}
    				temp += str[i];
    			}
    			else if (str[i] == '(') {
    				if (!temp.empty()) {
    					if (int_temp == 0) int_temp = 1;
    					insert_into_map(map_result, temp, int_temp);
    					temp.clear();
    					int_temp = 0;
    				}
    				int j = i;
    				int acc = 1;
    				while (acc != 0) {
    					j++;
    					if (str[j] == '(')acc++;
    					if (str[j] == ')') acc--;
    				}
    				auto result = ForParent(str.substr(i + 1, j - i - 1));
    				j++;
    				if (str[j] >= '0'&&str[j] <= '9'&&j < str.size()) {
    					while (str[j] >= '0'&&str[j] <= '9') {
    						int_temp = int_temp * 10 + str[j] - '0';
    						j++;
    					}
    				}
    				else int_temp = 1;
    				for (auto x : result) {
    					insert_into_map(map_result, x.first, x.second*int_temp);
    				}
    				temp.clear();
    				int_temp = 0;
    				i = j - 1;
    			}
    			i++;
    		}
    		if (!temp.empty()) {
    			insert_into_map(map_result, temp, 1);
    		}
    
    		return map_result;
    	}
    };
    

    Not the best implemention, but it works.
    The idea is, use a map to store string and value, and use recursion to solve parentheses.


Log in to reply
 

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