原题链接在这里: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. SpringBoot学习(1)

    内容概要: spring data springboot是spring团队基于spring4开发的一个框架. springboot来简化spring应用开发,约定大于配置,去繁从简,just run就 ...

  2. Python 基础教程

    Python 基础教程 Python是一种解释型.面向对象.动态数据类型的高级程序设计语言. Python由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年. 像P ...

  3. iPhone 和Android应用,特殊的链接:打电话,短信,email

    下面的这篇文章主要是说,网页中的链接如何写,可以激活电话的功能. 例如,页面中展示的是一个电话号码,当用户在手机浏览器里面点击这个电话号码的时候,手机会弹出拨号的面板,或者是短信程序会启动等. 1. ...

  4. mail_location not set and autodetection failed 解决方案[devecot, sendmail]

    安装dovecot比较简单, 但是也需要配置, 如果不进行任何配置时,在测试时会出现如下的提示: dovecot: pop3(wwufengg): Error: user wwufengg: Init ...

  5. 暗网 tor溯源困难根因——用户的请求会在分布全球的主机随机跳转三次,最终才到达服务器,这就造成了溯源的极其困难

    Tor(The Onion Router)可以说是目前最为流行的网络匿名访问技术,用户的请求会在分布全球的主机随机跳转三次,最终才到达服务器,这就造成了溯源的极其困难,从而使得所有的访问者完全没有身份 ...

  6. Linux中jar包指定端口启动并记录日志

    Linux中jar包指定端口启动并记录日志: java -jar -Dserver.port=38080  group-buying-0.0.1-SNAPSHOT.jar   >log.log ...

  7. bzoj3401

    题解: 单调栈 一个一个压入 然后比下面高就弹出 代码: #include<bits/stdc++.h> using namespace std; ; int n,tot,a[N],z[N ...

  8. 使用游标、存储过程、pivot 三种方法导入数据

    --使用游标循环 if (exists (select * from sys.objects where name = 'Base_RecordTend_Test')) drop proc Base_ ...

  9. RabbitMQ(6) 集群部署

    单节点部署 rabbitmq单节点部署比较简单,可以使用apt-get等工具快速安装部署. wget -O- https://www.rabbitmq.com/rabbitmq-release-sig ...

  10. SDP协议简述

    SDP协议也是文本协议,只需要按照协议本身的格式填充.SDP协议格式即详细信息如下: 会话描述 格式及举例 v=(protocol version) v=0 o=(owner/creator and ...