原题链接在这里: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. Microsoft's OWIN implementation, the Katana project

    参考: https://github.com/aspnet/AspNetKatana/ https://github.com/aspnet/AspNetKatana/wiki/Roadmap

  2. MS SQL2008执行大脚本文件时,提示“内存不足”的解决办法

    问题描述: 当客户服务器不允许直接备份时,往往通过导出数据库脚本的方式来部署-还原数据库, 但是当数据库导出脚本很大,用Microsoft SQL Server Management Studio执行 ...

  3. JXLS导出Excel(模板导出)

    1.导包 在pom.xml中加入依赖如下: <dependency> <groupId>org.jxls</groupId> <artifactId>j ...

  4. 奇怪的表达式求值 (java实现)

    题目参考:http://blog.csdn.net/fuxuemingzhu/article/details/68484749 问题描述; 题目描述: 常规的表达式求值,我们都会根据计算的优先级来计算 ...

  5. iptables详解(9):iptables的黑白名单机制

    注意:在参照本文进行iptables实验时,请务必在个人的测试机上进行,因为如果iptables规则设置不当,有可能使你无法连接到远程主机中. 前文中一直在强调一个概念:报文在经过iptables的链 ...

  6. Find the odd int

    Given an array, find the int that appears an odd number of times. There will always be only one inte ...

  7. Python中字符串、列表、元组、集合、字典中的一些知识,有些不太常见

    ————————笔记——————————# 字符串1. 字符串是不可变的.2. 字符串切片输出:`[start:end:step]`.使用`a[::-1]`倒序输出字符串.3. `str.split( ...

  8. innerHTML的兼容性

    问题描述: 给定一个表格,thead的内容一致,tbody的内容动态改变(内容,合并单元格等不同) 错误方案: 给tbody定义一个id,然后document.getElementById('id') ...

  9. MD5加密(java和c#)

    java代码 public static String md5(String str) { try { MessageDigest md = MessageDigest.getInstance(&qu ...

  10. SCM-MANAGER

    什么是SCM-MANAGER 基于Web的,集成了  Git. Mercurial .Subversion  多种代码管理工具的源代码管理平台 它有什么优点 简易安装 不需要破解配置文件,完全可配置的 ...