[LeetCode]726. Number of Atoms

来源:互联网 发布:云计算和大数据的区别 编辑:程序博客网 时间:2024/06/17 23:26

Description:

Given a chemical formula (given as a string), return the count of each atom.

An atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.

1 or more digits representing the count of that element may follow if the count is greater than 1. If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible.

Two formulas concatenated together produce another formula. For example, H2O2He3Mg4 is also a formula.

A formula placed in parentheses, and a count (optionally added) is also a formula. For example, (H2O2) and (H2O2)3 are formulas.

Given a formula, output the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.

Example 1:

Input: formula = "H2O"Output: "H2O"Explanation: The count of elements are {'H': 2, 'O': 1}.

Example 2:

Input: formula = "Mg(OH)2"Output: "H2MgO2"Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.

Example 3:

Input: formula = "K4(ON(SO3)2)2"Output: "K4N2O14S4"Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.

Note:

  • All atom names consist of lowercase letters, except for the first character which is uppercase.
  • The length of formula will be in the range [1, 1000].
  • formula will only consist of letters, digits, and round parentheses, and is a valid formula as defined in the problem.

    —————————————————————————————————————————————————

    Solution:

    题意:给定一个以字符串表示的化学表达式,求表达式中每个原子及其个数。

    思路:递归,也可以用栈,一样的思路。

    class Solution {private:    // 输入字符串:化学公式    string formula;    // 指针:指向formula当前位置    int start = 0;public:    string countOfAtoms(string formula) {        this->formula = formula;        // 递归得到化学公式里每个原子及其对应的个数,以哈希表map形式存储        map<string, int> relation = getAtomsRelation();        // 将得到的结果转成字符串输出:由于map按key的字典序保存,所以从头开始遍历        string result = "";        for (map<string, int>::iterator it = relation.begin(); it != relation.end(); it++) {            result += it->first;            // 将int转成string            if (it->second > 1) {                stringstream ss;                ss << it->second;                result += ss.str();            }        }        return result;    }    map<string, int> getAtomsRelation() {        // 创建当前递归的哈希表        map<string, int> cur;        while (start < formula.length()) {            // 遇到'('进入下一层递归,然后将递归的结果存入当前哈希表中            if (formula[start] == '(') {                start++;                map<string, int> inCur = getAtomsRelation();                for (map<string, int>::iterator it = inCur.begin(); it != inCur.end(); it++)                    cur[it->first] += it->second;                        // 遇到')'返回上一层递归,返回之前还要看看后面有没有数字,如果有,要将当前哈希表所有值乘以这个数再返回            } else if (formula[start] == ')') {                int j = start + 1, tempInt = 0;                while (j < formula.length() && formula[j] <= '9' && formula[j] >= '0') {                    tempInt *= 10;                    tempInt += formula[j] - '0';                    j++;                }                tempInt = tempInt == 0 ? 1 : tempInt;                                for (map<string, int>::iterator it = cur.begin(); it != cur.end(); it++)                    it->second *= tempInt;                                start = j;                return cur;                            // 遇到大写字母表示遇到新的原子,得到当前原子全名和对应数字,存入当前哈希表中            } else if (formula[start] >= 'A' && formula[start] <= 'Z') {                // 得到原子全名                int j = start + 1;                while (j < formula.length() && formula[j] >= 'a' && formula[j] <= 'z')                    j++;                string tempString = formula.substr(start, j - start);                                // 得到对应数字                int tempInt = 0;                while (j < formula.length() && formula[j] <= '9' && formula[j] >= '0') {                    tempInt *= 10;                    tempInt += formula[j] - '0';                    j++;                }                tempInt = tempInt == 0 ? 1 : tempInt;                                // 存入哈希表中                cur[tempString] += tempInt;                                start = j;            }        }        return cur;    }};