题目来源:https://leetcode-cn.com/problems/number-of-atoms/
大致题意:
给定一个化学式,统计每种原子出现的次数,并按字典序输出结果字符串
思路:
栈+哈希表:
首先压入一个空的哈希表进栈。然后对化学式字符串遍历,对于当前的每个字符,有三种情况:
- 当前字符为 ‘(’ ,则压入一个新的哈希表,统计括号内原子数量
- 当前字符为 ‘)’ ,统计括号外的数字,若没有则为1,然后将栈头部哈希表(也就是统计括号内原子数的哈希表)弹出,并将每个原子的统计数目乘上括号外数字后加入上一层(当前的栈头部哈希表)统计数目中
- 当前为正常原子字符,遍历出原子字符和数字,加入当前栈头部哈希表
代码:
public class CountOfAtoms {
String formula; // 存储formula便于其他方法使用
int n; // 存储formula长度
int idx; // 存储当前遍历的索引位置
public String countOfAtoms (String formula) {
this.formula = formula;
this.n = formula.length();
this.idx = 0;
Deque<Map<String, Integer>> stack = new LinkedList<Map<String, Integer>>(); // 创建一个以HashMap为元素的栈
stack.push(new HashMap<String, Integer>()); // 压入第一个HashMap
while (idx < n) {
if (formula.charAt(idx) == '(') { // 碰到左括号,新压入一个HashMap统计括号内原子数量
stack.push(new HashMap<String, Integer>());
idx++;
}
else if (formula.charAt(idx) == ')') { // 碰到右括号,将对应括号内原子数统计值加到上一层统计内容中
idx++;
int num = parseNum(); // 先检索括号后是不是数字
Map<String, Integer> popMap = stack.pop(); // 将之前存储括号内的原子统计数的HashMap弹出
Map<String, Integer> topMap = stack.peek(); // 获取上一层(当前顶部)统计数的HashMap
for (Map.Entry<String, Integer> entry : popMap.entrySet()) {
String atom = entry.getKey();
int count = entry.getValue();
topMap.put(atom, topMap.getOrDefault(atom, 0) + count * num); // 括号内的原子数需要乘上括号外的数字再加入上一层的统计数
}
}
else { // 遍历原子
String atom = parseAtom();
int num = parseNum();
Map<String, Integer> topMap = stack.peek(); // 获取将要统计数量的HashMap
topMap.put(atom, topMap.getOrDefault(atom, 0) + num); // 统计原子数量
}
}
// 将HashMap结果处理为输出结果
Map<String, Integer> map = stack.pop();
// TreeMap内容有序,对于字符串默认字典序
TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>(map);
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
String atom = entry.getKey();
int num = entry.getValue();
sb.append(atom);
if (num > 1) // 如果数目不为1想要加上数字
sb.append(num);
}
return sb.toString();
}
public String parseAtom() {
StringBuffer sb = new StringBuffer();
sb.append(formula.charAt(idx++)); // 先添加首字母
while (idx < n && Character.isLowerCase(formula.charAt(idx))) {
sb.append(formula.charAt(idx++)); // 如果有跟小写字母,加上
}
return sb.toString();
}
public int parseNum() {
if (idx == n || !Character.isDigit(formula.charAt(idx))) {
return 1; // 如果当前遍历结束,或者原子后未跟数字,返回1
}
int num = 0;
while (idx < n && Character.isDigit(formula.charAt(idx))) {
num = num * 10 + formula.charAt(idx++) - '0'; // 遍历计算数字
}
return num;
}
}
收获
- 括号或序列相关题目,使用递归或栈,找出问题结构设计代码
- Deque: 双向队列,支持插入删除元素的线性集合,可做栈
- Deque栈的常规操作:pop、push、peek
- HashMap的遍历方法:for (Map.Entry<K,V> entry : map.entrySet())
- TreeMap:适用于按自然顺序或自定义顺序(数字顺序,字典顺序)遍历键