LeetCode 题解工作台
原子的数量
给你一个字符串化学式 formula ,返回 每种原子的数量 。 原子总是以一个大写字母开始,接着跟随 0 个或任意个小写字母,表示原子的名字。 如果数量大于 1,原子后会跟着数字表示原子的数量。如果数量等于 1 则不会跟数字。 例如, "H2O" 和 "H2O2" 是可行的,但 "H1O2" 这个…
4
题型
3
代码语言
3
相关题
当前训练重点
困难 · 栈·状态
答案摘要
class Solution { public String countOfAtoms(String formula) {
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
给你一个字符串化学式 formula ,返回 每种原子的数量 。
原子总是以一个大写字母开始,接着跟随 0 个或任意个小写字母,表示原子的名字。
如果数量大于 1,原子后会跟着数字表示原子的数量。如果数量等于 1 则不会跟数字。
- 例如,
"H2O"和"H2O2"是可行的,但"H1O2"这个表达是不可行的。
两个化学式连在一起可以构成新的化学式。
- 例如
"H2O2He3Mg4"也是化学式。
由括号括起的化学式并佐以数字(可选择性添加)也是化学式。
- 例如
"(H2O2)"和"(H2O2)3"是化学式。
返回所有原子的数量,格式为:第一个(按字典序)原子的名字,跟着它的数量(如果数量大于 1),然后是第二个原子的名字(按字典序),跟着它的数量(如果数量大于 1),以此类推。
示例 1:
输入:formula = "H2O"
输出:"H2O"
解释:原子的数量是 {'H': 2, 'O': 1}。
示例 2:
输入:formula = "Mg(OH)2"
输出:"H2MgO2"
解释:原子的数量是 {'H': 2, 'Mg': 1, 'O': 2}。
示例 3:
输入:formula = "K4(ON(SO3)2)2"
输出:"K4N2O14S4"
解释:原子的数量是 {'K': 4, 'N': 2, 'O': 14, 'S': 4}。
提示:
1 <= formula.length <= 1000formula由英文字母、数字、'('和')'组成formula总是有效的化学式
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N log N) due to sorting the final element counts, and space complexity is O(N) to store stack states and the hash table for all elements. |
| 空间 | O(N) |
面试官常问的追问
外企场景- question_mark
Candidate identifies stack usage for nested parentheses immediately.
- question_mark
Correctly extracts element names and numeric counts without off-by-one errors.
- question_mark
Merges counts and produces lexicographical output cleanly.
常见陷阱
外企场景- error
Misparsing multi-letter elements or ignoring lowercase letters.
- error
Failing to apply multipliers to entire nested groups correctly.
- error
Returning counts of 1 explicitly instead of omitting them in output.
进阶变体
外企场景- arrow_right_alt
Formulas with deeply nested parentheses to stress stack usage.
- arrow_right_alt
Formulas with long sequences of the same element to test aggregation logic.
- arrow_right_alt
Formulas with missing multipliers to check default count handling.