#726 Number of Atoms

Description

Given a string formula representing a chemical formula, return the count of each atom.

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

One or more digits representing that element’s count 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 are concatenated together to 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.

Return 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.

The test cases are generated so that all the values in the output fit in a 32-bit integer.

Examples

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}.

Constraints:

1 <= formula.length <= 1000
formula consists of English letters, digits, ‘(’, and ‘)’.
formula is always valid.

思路

感觉这个虽然是hard,但其实只要把逻辑理清楚了就行,括号内先处理什么的,要多调试,很难一次直接出结果,也没什么好说的

代码

class Solution {  
    public int findRightPair(String formula){
        Stack<String> parentheses = new Stack<>();
        parentheses.push("(");
        
        int i = 0;
        while (!parentheses.empty()){
            i++;
            if (formula.charAt(i) == ')')
                parentheses.pop();
            if (formula.charAt(i) == '(')
                parentheses.push("(");
        }
        
        return i;
    }
    
    public Map<String, Integer> countElement(String formula){
        Map<String, Integer> count = new TreeMap<>();
        
        // 如果碰到括号就先处理括号内(这里要用while)
        while (formula.charAt(0) == '('){
        	// 要自己编写findRightPair函数,通过stack来判断最右括号在哪里
            int rightPair = findRightPair(formula);
        
            int digitBoundary = rightPair + 1;
            while (digitBoundary < formula.length() && formula.charAt(digitBoundary) >= '0' && formula.charAt(digitBoundary) <= '9')
                digitBoundary ++;

            int times = 1;
            if (digitBoundary != rightPair + 1)
                times = Integer.valueOf(formula.substring(rightPair + 1, digitBoundary));

            // 内层交给countElement
            Map<String, Integer> inside = countElement(formula.substring(1, rightPair));
            for (String key: inside.keySet()){
                count.put(key, inside.get(key) * times + count.getOrDefault(key, 0));
            }

            formula = formula.substring(digitBoundary);
            
            // 判断如果formula结束了,就直接返回count
            if (formula == "")
                return count;
        }
        
        // 计算element
        int lowerCaseBoundary = 1;
        while (lowerCaseBoundary < formula.length() && formula.charAt(lowerCaseBoundary) >= 'a' && formula.charAt(lowerCaseBoundary) <= 'z')
            lowerCaseBoundary ++;
        String keyElement = formula.substring(0, lowerCaseBoundary);
        
        // 计算element数量
        int digitBoundary = lowerCaseBoundary;
        while (digitBoundary < formula.length() && formula.charAt(digitBoundary) >= '0' && formula.charAt(digitBoundary) <= '9')
            digitBoundary ++;
        int times = 1;
        if (digitBoundary > lowerCaseBoundary)
            times = Integer.valueOf(formula.substring(lowerCaseBoundary, digitBoundary));
        
        // 把这个element放到count里面
        count.put(keyElement, count.getOrDefault(keyElement, 0) + times);
        
        // 如果没有到达末尾就递归计算
        Map<String, Integer> more = new TreeMap<>();
        if (digitBoundary != formula.length())
            more = countElement(formula.substring(digitBoundary));
        
        // 把more塞到count里面
        for (String key: more.keySet()){
            count.put(key, more.get(key) + count.getOrDefault(key, 0));
        }
        
        return count;
    }
    
    public String countOfAtoms(String formula) {
        Map<String, Integer> count = countElement(formula);
        String answer = "";
        
        for (String key: count.keySet()){
            answer = answer + key;
            if (count.get(key) != 1)
                answer = answer + count.get(key);
        }
        
        return answer;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值