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

class Solution {
    public String countOfAtoms(String formula) {
        Stack<Map<String,Integer>> stack= new Stack<>();
        Map<String,Integer> map= new HashMap<>();
        int i=0,n=formula.length();
        while(i<n){
            char c=formula.charAt(i);i++;
            if(c==‘(‘){
                stack.push(map);
                map=new HashMap<>();
            }
            else if(c==‘)‘){
                int val=0;
                while(i<n && Character.isDigit(formula.charAt(i)))
                    val=val*10+formula.charAt(i++)-‘0‘;

                if(val==0) val=1;
                if(!stack.isEmpty()){
                Map<String,Integer> temp= map;
                map=stack.pop();
                    for(String key: temp.keySet())
                        map.put(key,map.getOrDefault(key,0)+temp.get(key)*val);
                }
            }
            else{
                int start=i-1;
                while(i<n && Character.isLowerCase(formula.charAt(i))){
                 i++;
                }
                String s= formula.substring(start,i);
                int val=0;
                while(i<n && Character.isDigit(formula.charAt(i))) val=val*10+ formula.charAt(i++)-‘0‘;
                if(val==0) val=1;
                map.put(s,map.getOrDefault(s,0)+val);
            }
        }
        StringBuilder sb= new StringBuilder();
        List<String> list= new ArrayList<>(map.keySet());
        Collections.sort(list);
        for(String key: list){
            sb.append(key);
          if(map.get(key)>1) sb.append(map.get(key));
                                    }
        return sb.toString();
    }
}

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9914477.html

时间: 2024-12-20 00:28:01

726. Number of Atoms的相关文章

【leetcode】726. Number of Atoms

题目如下: 解题思路:我用的是递归的方法,每次找出与第一个')'匹配的'('计算atom的数量后去除括号,只到分子式中没有括号为止.例如 "K4(ON(SO3)2)2" -> "K4(ONS2O6)2" -> "K4O2N2S4O12".接下来再对分子式进行分割,得出每个atom的数量后排序即可.原理很简单,代码写得很乱,仅供参考. 代码如下: class Solution(object): def recursive(self,fo

[LeetCode] 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 elem

LeetCode Problems List 题目汇总

No. Title Level Rate 1 Two Sum Medium 17.70% 2 Add Two Numbers Medium 21.10% 3 Longest Substring Without Repeating Characters Medium 20.60% 4 Median of Two Sorted Arrays Hard 17.40% 5 Longest Palindromic Substring Medium 20.70% 6 ZigZag Conversion Ea

Molecule to atoms

For a given chemical formula represented by a string, count the number of atoms of each element contained in the molecule and return an object. 1 water = 'H2O' 2 parse_molecule(water) 3 # return {H: 2, O: 1} 4 5 magnesium_hydroxide = 'Mg(OH)2' parse_

SPOJ ATOMS - Atoms in the Lab

题目链接:http://www.spoj.com/problems/ATOMS/ 题目大意:有N个原子,他们每秒分裂成K个新原子,新原子也能继续分裂.问如果要控制他的数量为M以内,应在什么时候使其停止分裂.其实时间为0. 解题思路:可以发现其实就是一个求log的公式,只不过需要注意M小于N的情况. 代码: 1 const int maxn = 1e6 + 5; 2 ll n, k, m; 3 4 void solve(){ 5 if(m < n) { 6 cout << 0 <&l

【LeetCode】栈 stack(共40题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [20]Valid Parentheses [42]Trapping Rain Water [71]Simplify Path [84]Largest Rectangle in Histogram [85]Maximal Rectangle [94]Binary Tree Inorder Traversal [103]Binary Tree Zigzag Level

【LeetCode】哈希表 hash_table(共88题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [1]Two Sum (2018年11月9日,k-sum专题,算法群衍生题) 给了一个数组 nums, 和一个 target 数字,要求返回一个下标的 pair, 使得这两个元素相加等于 target . 题解:我这次最大范围的优化代码, hash-table + one pass,时间复杂度 O(N),空间复杂度 O(N).重点在于动态找,一边生成hash-tabl

Pattern类(java JDK源码记录)

1 /* 2 * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved. 3 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 * 21 * 22 * 23 *

11 Python Libraries You Might Not Know

11 Python Libraries You Might Not Know by Greg | January 20, 2015 There are tons of Python packages out there. So many that no one man or woman could possibly catch them all. PyPi alone has over 47,000 packages listed! Recently, with so many data sci