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:
1
Input: formula = "H2O"
2
3
Output: "H2O"
4
5
Explanation:
6
The count of elements are {'H': 2, 'O': 1}.
Copied!
Example 2:
1
Input:
2
formula = "Mg(OH)2"
3
4
Output: "H2MgO2"
5
6
Explanation:
7
The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
Copied!
Example 3:
1
Input:
2
formula = "K4(ON(SO3)2)2"
3
4
Output: "K4N2O14S4"
5
6
Explanation:
7
The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
Copied!
Note:
All atom names consist of lowercase letters, except for the first character which is uppercase.
The length offormulawill be in the range[1, 1000].
formulawill 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. 分三种情况处理:
  1. 1.
    如果当前字符是'(',则压栈,更新treemap
  2. 2.
    如果当前字符是')',将当前map的内容保存到temp这个map,从stack中出栈得到之前的map,然后得到')'后面的数字,如果‘)'后面没有数字,则默认是1,再将数字乘以 temp里atom对应的数目,再将相应的结果放在map里
  3. 3.
    如果字符不是括号,则分别取得atom的名字和跟在其后的数字。需要注意的是,化学原子名字都是首写是大写字母,如果这个名字长度大于1的话,其后的字母都是小写,根据这个特点,我们可以知道 OH 分别代表 O和H这两个化学元素
1
class Solution {
2
public String countOfAtoms(String formula) {
3
if (formula == null || formula.length() == 0) {
4
return formula;
5
}
6
7
int index = 0;
8
Stack<TreeMap<String, Integer>> stack = new Stack<>();
9
TreeMap<String, Integer> map = new TreeMap<>();
10
int n = formula.length();
11
12
while (index < n) {
13
char c = formula.charAt(index);
14
15
if (c == '(') {
16
++index;
17
stack.push(map);
18
map = new TreeMap<>();
19
}
20
else if (c == ')') {
21
++index;
22
TreeMap<String, Integer> temp = map;
23
map = stack.pop();
24
25
// Get the number following ')'
26
int count = 0;
27
while (index < formula.length() && Character.isDigit(formula.charAt(index))) {
28
count = 10 * count + formula.charAt(index) - '0';
29
++index;
30
}
31
32
// If there is no number, it is default to 1
33
count = count == 0 ? 1 : count;
34
35
for (String name : temp.keySet()) {
36
map.put(name, map.getOrDefault(name, 0) + temp.get(name) * count);
37
}
38
}
39
else {
40
StringBuilder name = new StringBuilder();
41
// Get the first letter (Capital)
42
name.append(formula.charAt(index));
43
++index;
44
45
// If the atom name has lowercase letter, append it to stringbuilder
46
while (index < n && Character.isLowerCase(formula.charAt(index))) {
47
name.append(formula.charAt(index));
48
++index;
49
}
50
51
// Get the number of atoms following the atom
52
int count = 0;
53
while (index < n && Character.isDigit(formula.charAt(index))) {
54
count = 10 * count + formula.charAt(index) - '0';
55
++index;
56
}
57
58
// If there is no number, it is default to 1
59
count = count == 0 ? 1 : count;
60
map.put(name.toString(), map.getOrDefault(name.toString(), 0) + count);
61
}
62
}
63
64
StringBuilder res = new StringBuilder();
65
for (String name : map.keySet()) {
66
res.append(name);
67
int count = map.get(name);
68
if (count > 1) {
69
res.append(count);
70
}
71
}
72
return res.toString();
73
}
74
}
Copied!

3. Time & Space Complexity

Stack: 时间复杂度O(n), 空间复杂度O(n)