原题链接https://leetcode.com/problems/number-of-atoms/

题目描述

Given a chemical formula (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:

Input:
formula = “H2O”
Output: “H2O”
Explanation:
The count of elements are {‘H’: 2, ‘O’: 1}.

Example 2:

Input:
formula = “Mg(OH)2”
Output: “H2MgO2”
Explanation:
The count of elements are {‘H’: 2, ‘Mg’: 1, ‘O’: 2}.

Example 3:

Input:
formula = “K4(ON(SO3)2)2”
Output: “K4N2O14S4”
Explanation:
The count of elements are {‘K’: 4, ‘N’: 2, ‘O’: 14, ‘S’: 4}.

Note:
All atom names consist of lowercase letters, except for the first character which is uppercase.
The length of formula 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.

思路分析

把给定化学式的原子数目分别统计出来,并返回原子和对应数目组成的字符串。
类似之前做的计算器,都是在于括号的嵌套,可以通过递归或者栈,其实两者思想上差不多啦

下面贴的题解是小陌看了花花酱大神之后的优化版,好多新特性自己还没有去使用的意识,还是用之前本方法,差距呐ヽ(。>д<)p
here are花花酱大神http://zxi.mytechroad.com/blog/string/leetcode-726-number-of-atoms/

AC解

class Solution {
private int i;
public String countOfAtoms(String formula) {
i = 0;
StringBuilder res = new StringBuilder();
Map<String,Integer> map = parse(formula); for(String s:map.keySet())
{
res.append(s);
int number = map.get(s);
if(number > 1)
{
res.append("" + number);
}
} return res.toString();
} public Map<String,Integer> parse(String f)
{
Map<String,Integer> tm = new TreeMap();
while( i<f.length() && f.charAt(i) != ')')
{
if(f.charAt(i) == '(')
{
i ++;
for(Map.Entry<String,Integer> tra : parse(f).entrySet())
{
tm.put(tra.getKey(),tm.getOrDefault(tra.getKey(),0) + tra.getValue());
}
}
else
{
int begin = i ++;
while(i<f.length() && Character.isLowerCase(f.charAt(i)))
{
i ++;
} String atom = f.substring(begin,i);
begin = i;
while(i<f.length() && Character.isDigit(f.charAt(i)))
{
i ++;
} int count = begin < i ? Integer.parseInt(f.substring(begin,i)) : 1;
tm.put(atom,tm.getOrDefault(atom,0) + count);
}
} int begin = ++ i;
while(i<f.length() && Character.isDigit(f.charAt(i)))
{
i ++;
}
if(begin < i)
{
int count = Integer.parseInt(f.substring(begin,i));
for(String s:tm.keySet())
{
tm.put(s,tm.get(s)*count);
}
} return tm;
}
}

Number of Atoms——LeetCode进阶路的更多相关文章

  1. 【LeetCode】726. Number of Atoms 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/number-o ...

  2. [LeetCode] Number of Atoms 原子的个数

    Given a chemical formula (given as a string), return the count of each atom. An atomic element alway ...

  3. LeetCode Number of Atoms

    原题链接在这里:https://leetcode.com/problems/number-of-atoms/description/ 题目: Given a chemical formula (giv ...

  4. 【leetcode】726. Number of Atoms

    题目如下: 解题思路:我用的是递归的方法,每次找出与第一个')'匹配的'('计算atom的数量后去除括号,只到分子式中没有括号为止.例如 "K4(ON(SO3)2)2" -> ...

  5. [Swift]LeetCode726. 原子的数量 | Number of Atoms

    Given a chemical formula (given as a string), return the count of each atom. An atomic element alway ...

  6. Number of Islands——LeetCode

    Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...

  7. 阿里巴巴 web前端性能优化进阶路

    Web前端性能优化WPO,相信大多数前端同学都不会陌生,在各自所负责的站点页面中,也都会或多或少的有过一定的技术实践.可以说,这个领域并不缺乏成熟技术理论和技术牛人:例如Yahoo的web站点性能优化 ...

  8. LeetCode.874-走路机器人模拟(Walking Robot Simulation)

    这是悦乐书的第335次更新,第360篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第205题(顺位题号是874).网格上的机器人从点(0,0)开始并朝北.机器人可以接收三 ...

  9. 瑞柏匡丞谈中国移动app的国际进阶路

    当今3.0互联时代,已然形成了一个移动化,互动化,全球化的完整体系.瑞柏匡丞也在常年与国内外客户的交流沟通中有了自己的些许见解. 国内的移动产业的发展已然非常迅速,但也正是因为各类企业的不断崛起,能够 ...

  10. App开发革命进阶路

    APP开发的成败,或许不是程序编辑的多么完美,界面设计的多么精致,其实这就是一场用户体验的革命. APP的使用场景是移动设备,人机交互以单指手“触点”为主,大段文字输入是交互的禁区.因此,APP带来了 ...

随机推荐

  1. 使用mybatis-plus转换枚举值

    1. 使用mybatis-plus转换枚举值 枚举值转换方式有很多,有以下方式: 后端写一个通用方法,只要前端传枚举类型,后端返回相应的枚举值前端去匹配 优点:能够实时保持数据一致性 缺点:如果有大量 ...

  2. JS中的0和php中的0

    请注意:包含 0 的字符串 "0" 是 true 一些编程语言(比如 PHP)视 "0" 为 false.但在 JavaScript 中,非空的字符串总是 tr ...

  3. 什么是CPU?

    当你用手机刷短视频.用电脑玩游戏,或是使用智能手表查看健康数据时,这些设备的核心"大脑"--CPU(中央处理器)正在默默工作.它是现代计算设备的核心,但很多人对它一知半解.今天我们 ...

  4. postman 如何比较两台电脑的脚本是否一样

  5. SpringSecurity5(1-快速入门)

    依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spri ...

  6. PaddleOCR学习笔记3-通用识别服务

    今天优化了下之前的初步识别服务的python代码和html代码. 采用flask + paddleocr+ bootstrap快速搭建OCR识别服务. 代码结构如下: 模板页面代码文件如下: uplo ...

  7. Pydantic Mixin:构建可组合的验证系统体系

    title: Pydantic Mixin:构建可组合的验证系统体系 date: 2025/3/22 updated: 2025/3/22 author: cmdragon excerpt: Pyda ...

  8. StringBuilder的介绍、构造方法及成员方法

    1.StringBuilder的介绍 1.StringBuilder是字符串缓冲区,可以认为是一种容器,能装任何类型的数据,但被装入的数据都会变为字符串 如图 无论是什么类型的数据,被装入字符串缓冲区 ...

  9. C# Socket教程入门,Socket的使用方法,附可执行Demo

    核心: 在服务器端和客户端的两个Socket实例,共同维持一个连接,而我们还需要一个服务端绑定了特定端口号的固定的serverSocket,用来监听远方clientSocket的申请,并为这个申请建立 ...

  10. 调用 restful的api的方法

    var // myurl : string; tmpstr : String;// string; RespData :TStringStream; sendData : TStringList; j ...