原题链接在这里: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. [Vue]组件——插槽:slot(匿名插槽,具名插槽)与slot-scope(作用域插槽)

    1.单个插槽 | 匿名插槽 1.1<navigation-link> 子组件定义为: <a v-bind:href="url" class="nav-l ...

  2. TestNG入门--安装和基本介绍

    TestNG介绍 TestNG是Java中的一个测试框架, 类似于JUnit 和NUnit,   功能都差不多, 只是功能更加强大,使用也更方便 Java中已经有一个JUnit的测试框架了.  Tes ...

  3. nyoj164——卡特兰数(待填坑)

    题意:将1~2n个数按照顺时针排列好,用一条线将两个数字连接起来要求:线之间不能有交点,同一个点只允许被连一次. 最后问给出一个n,有多少种方式满足条件. 卡特兰数(列): 令h(0)=1,h(1)= ...

  4. Windows 系统cmd设置添加静态路由方式

    电脑上添加静态路由,cmd设置路由 方法/步骤 1.首先在“运行”窗口输入cmd(按WIN+R打开运行窗口),然后回车进入命令行,输入 route  add  10.253.251.0  mask   ...

  5. [转载]Java在线打开PDF文档

    步骤一:(涉及到的工具) 访问:http://www.zhuozhengsoft.com/dowm/,从官网下载PageOffice for Java. 步骤二:(配置工程) 1. 解压PageOff ...

  6. sql复制表结构及复制表数据

    一.复制表结构 假设我们有一个数据表Person,有Id,FirstName,LastName,Weight,Height5个列,表结构可以参考这一篇.现在我们想创建一个新表叫People,表结构和P ...

  7. MYSQL-实现分组排序 对比 ORACLE 和SQLserver用 row_number() over(partition by ) 分组排序功能

    以下是个人笔记: 本文是为了理解 row_number() over(partition by )  和实现各种数据库的分组排序功能 select ROW_NUMBER()over( partitio ...

  8. Java复习9网路编程

    Java 复习9网路编程 20131008 前言: Java语言在网络通信上面的开发要远远领先于其他编程语言,这是Java开发中最重要的应用,可以基于协议的编程,如Socket,URLConnecti ...

  9. NEU 1495 a interesting game 大数 难度:1

    问题 G: a interesting game 时间限制: 1 Sec  内存限制: 128 MB提交: 29  解决: 10[提交][状态][讨论版] 题目描述 One day,Kid is in ...

  10. hdu 2818 Building Block(并查集,有点点复杂)

    Building Block Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)To ...