LeetCode 题解工作台

原子的数量

给你一个字符串化学式 formula ,返回 每种原子的数量 。 原子总是以一个大写字母开始,接着跟随 0 个或任意个小写字母,表示原子的名字。 如果数量大于 1,原子后会跟着数字表示原子的数量。如果数量等于 1 则不会跟数字。 例如, "H2O" 和 "H2O2" 是可行的,但 "H1O2" 这个…

category

4

题型

code_blocks

3

代码语言

hub

3

相关题

当前训练重点

困难 · 栈·状态

bolt

答案摘要

class Solution { public String countOfAtoms(String formula) {

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串化学式 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 <= 1000
  • formula 由英文字母、数字、'('')' 组成
  • formula 总是有效的化学式
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

原子的数量题解:栈·状态 | LeetCode #726 困难