726. Number of Atoms


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.

方法1: recursion

huahua:http://zxi.mytechroad.com/blog/string/leetcode-726-number-of-atoms/
grandyang: https://www.cnblogs.com/grandyang/p/8667239.html

思路:

首先举个栗子:K4(ON(SO3)2)2,先提取K, 随后发现K的个数是4,记录下来。此时遇到了‘(’,开始递归求解子问题ON(SO3)2。同样的,先记录O, N 各有一个,再次遇到‘(’,递归求解SO3,得到{S: 1, O: 3}。这时遍历遇到了’)’,是返回到上层函数的时候,我们返回的应该是当前层所累计的这个{S: 1, O: 3}的map,这样在返回上层后,我们继续读取到2这个数字,将{S: 1, O: 3} * 2 变成{S: 2, O: 6},并与当前层之前统计的{N: 1, O: 1}合并,再次遇到‘)’,继续放回{N: 1, O: 7, S: 1},读取数字2,{N: 1, O: 7, S: 1}* 2 变成 {N: 2, O: 14, S: 2},与{K: 4}合并,得到 {K: 1, N: 2, O: 14, S: 2} 即为最终结果。那么这个过程中一共有如下几个子问题:在当前层中读取元素getElement, 读取数字getNumber,遇到‘(’发起递归,遇到‘)’返回map。其中前两个子问题我们可以拆解出两个函数,再和后两个一起放进主函数中处理。这个过程中要来回传递一个reference来标记当前指针指向的坐标每一个子过程都有义务维护这个指针。

易错点:

  1. get name 和get number的顺序matters:由于已知表达式合法,我们一定是每次先读name再读num,如果反过来,会造成错误。
  2. get number中,默认的值是1:也就是说,即使i没有移动位置,返回的num至少是1,比如OH。
  3. get name中,允许Mg这种大写 + 小写 * n的名称出现:首先判断name是否为空,如果不为空的话,可以继续接受小写字母,否则要终止并返回当前读入的name。
  4. 最后生成result的时候,只有1个原子的case不用打出“1”。
class Solution {
public:
    string countOfAtoms(string formula) {
        string result;
        int i = 0;
        auto hash = countHelper(formula, i);
        for (auto a: hash) {
            result += a.first + ((a.second == 1) ? "" : to_string(a.second));
        }
        return result;
    }
    
    map<string, int> countHelper(string & formula, int & i) {
        map<string, int> hash;
        int num = 0;
        string name;
        while (i < formula.size()) {
            if (formula[i] == '(') {
                i++;
                auto hash_sub = countHelper(formula, i);
                int rep = getNumber(formula, i);
                // multiply and merge
                for (auto & p: hash_sub) {
                    hash[p.first] += p.second * rep;
                }
            } 
            else if (formula[i] == ')') {
                i++;
                return hash;
            }
            else {
                // order matters name >> num 
                name = getName(formula, i);
                num = getNumber(formula, i);
                hash[name] += num;
            }
        }
        return hash;
    }
    
    string getName(string & formula, int & i) {
        string name;
        while (i < formula.size() && isalpha(formula[i])) {
            if (name.empty() || islower(formula[i])) name += formula[i++];
            else return name;
        }
        return name;
    }
    
    int getNumber(string & formula, int & i) {
        int num = 0;
        while (i < formula.size() && isdigit(formula[i])) {
            num = num * 10 + formula[i++] - '0';
        }
        return num == 0 ? 1 : num;
    }
};

方法2: stack

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值