726 Number of Atoms
726. Number of Atoms
1. Question
Given a chemicalformula
(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:
Example 2:
Example 3:
Note:
All atom names consist of lowercase letters, except for the first character which is uppercase.
The length offormula
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.
2. Implementation
(1) Stack
思路: 这题和394很类似,像这些带有匹配括号,括号里有subproblem的题,基本可以用递归或者stack处理。用stack的话,由于题目要求返回的结果要按照atom name升序排序,并且要记录每个atom的数目,所以我们用TreeMap,而stack里放的也是TreeMap. 分三种情况处理:
如果当前字符是'(',则压栈,更新treemap
如果当前字符是')',将当前map的内容保存到temp这个map,从stack中出栈得到之前的map,然后得到')'后面的数字,如果‘)'后面没有数字,则默认是1,再将数字乘以 temp里atom对应的数目,再将相应的结果放在map里
如果字符不是括号,则分别取得atom的名字和跟在其后的数字。需要注意的是,化学原子名字都是首写是大写字母,如果这个名字长度大于1的话,其后的字母都是小写,根据这个特点,我们可以知道 OH 分别代表 O和H这两个化学元素
3. Time & Space Complexity
Stack: 时间复杂度O(n), 空间复杂度O(n)
Last updated