原题链接在这里:https://leetcode.com/problems/number-of-atoms/description/

题目:

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.

题解:

每当遇到'(', 代表更深的一层开始, 遇到')'表示本层的结束.

对于每一层用map来计数出现的元素和对应的count. 当一层结束,就把本层的map值加回到上层中.

保留上一层就用到了stack.

Time Complexity: O(n). n = formula.length().

Space: O(n).

AC Java:

 class Solution {
public String countOfAtoms(String formula) {
if(formula == null || formula.length() == 0){
return formula;
} int len = formula.length(); // stack里存的是本层元素和对应的count
Stack<Map<String, Integer>> stk = new Stack<Map<String, Integer>>();
stk.push(new TreeMap<String, Integer>()); int i = 0;
while(i<len){
if(formula.charAt(i) == '('){
// 遇到'('就说明到了新的一层,需要放新的stack
stk.push(new TreeMap<String, Integer>());
i++;
}else if(formula.charAt(i) == ')'){
// 遇到')'说明本层结束, 找到乘数, 计算结果加回到上层stack中
Map<String, Integer> top = stk.pop();
i++;
int iStart = i;
while(i<len && Character.isDigit(formula.charAt(i))){
i++;
} int multi = 1;
if(i > iStart){
multi = Integer.valueOf(formula.substring(iStart, i));
} Map<String, Integer> currentTop = stk.peek();
for(String s : top.keySet()){
int value = top.get(s);
currentTop.put(s, currentTop.getOrDefault(s, 0) + value*multi);
}
}else{
int iStart = i++;
while(i<len && Character.isLowerCase(formula.charAt(i))){
i++;
} String name = formula.substring(iStart, i); iStart = i;
while(i<len && Character.isDigit(formula.charAt(i))){
i++;
}
int multi = i>iStart ? Integer.valueOf(formula.substring(iStart, i)) : 1;
Map<String, Integer> currentTop = stk.peek();
currentTop.put(name, currentTop.getOrDefault(name, 0) + multi);
}
} StringBuilder sb = new StringBuilder();
Map<String, Integer> currentTop = stk.peek();
for(String name : currentTop.keySet()){
sb.append(name);
int value = currentTop.get(name);
if(value > 1){
sb.append(value);
}
} return sb.toString();
}
}

LeetCode Number of Atoms的更多相关文章

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

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

  2. 2016.5.15——leetcode:Number of 1 Bits ,

    leetcode:Number of 1 Bits 代码均测试通过! 1.Number of 1 Bits 本题收获: 1.Hamming weight:即二进制中1的个数 2.n &= (n ...

  3. LeetCode——Number Complement

    LeetCode--Number Complement Question Given a positive integer, output its complement number. The com ...

  4. LeetCode——Number of Boomerangs

    LeetCode--Number of Boomerangs Question Given n points in the plane that are all pairwise distinct, ...

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

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

  6. 【leetcode】726. Number of Atoms

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

  7. [LeetCode] Number of Boomerangs 回旋镖的数量

    Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of po ...

  8. [LeetCode] Number of Segments in a String 字符串中的分段数量

    Count the number of segments in a string, where a segment is defined to be a contiguous sequence of ...

  9. [LeetCode] Number of Connected Components in an Undirected Graph 无向图中的连通区域的个数

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

随机推荐

  1. 定时模块app_timer用法及常见问题—nRF5 SDK模块系列二

    app_timer是大家经常用到的一个库,app_timer的功能就是定时,也就是说,你在某一时刻启动一个app timer并设定超时时间,超时时间一到,app_timer就会回调timeout ha ...

  2. hand first python 选读(1)

    列表(list) 基本操作 比如说我要整理一个近期热映的电影列表: movies = ["venom", "My Neighbor Totor", " ...

  3. spring mvc: Hibernate验证器(字段不能为空,在1-150自己)

    spring mvc: Hibernate验证器(字段不能为空,在1-150自己) 准备: 下载Hibernate Validator库 - Hibernate Validator.解压缩hibern ...

  4. slim(4621✨)

    用于代码瘦身. 老鸟建议:不要混写js 和 html,如果避免不了,当前文件可以改为erb格式,混用slim和erb不是什么问题. git:  https://github.com/slim-temp ...

  5. 转载:Javascript面向对象编程原理 -- 理解对象

    源地址:http://www.html-js.com/article/1717 虽然JavaScript中已经自带了很多内建引用类型,你还是会很频繁的需要创建自己的对象.JavaScript编程的很大 ...

  6. torch 深度学习 (2)

    torch 深度学习 (2) torch ConvNet 前面我们完成了数据的下载和预处理,接下来就该搭建网络模型了,CNN网络的东西可以参考博主 zouxy09的系列文章Deep Learning ...

  7. 十四 web爬虫讲解2—Scrapy框架爬虫—豆瓣登录与利用打码接口实现自动识别验证码

    打码接口文件 # -*- coding: cp936 -*- import sys import os from ctypes import * # 下载接口放目录 http://www.yundam ...

  8. Spring3.0 核心jar包详解

    org.springframework.aop  包含在应用中使用Spring的AOP特性时所需的类. org.springframework.asm   Spring独立的ASM程序, Spring ...

  9. 搭建多master的saltstack环境

    0.16.0版本的发布,带来了minion可以连接多Master的特性. 这种方式称为多master( multi-master )配置, 使环境中的SaltStack冗余.在这种配置下,Salt M ...

  10. 从HDC转换到leptonica PIX

    void CAssistDlg::OnBnClickedTest() { HDC hdc = ::GetDC(NULL); HDC hdcMem = CreateCompatibleDC(hdc); ...