原题链接在这里: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. 互联网公司面试必问的Redis题目

    Redis是一个非常火的非关系型数据库,火到什么程度呢?只要是一个互联网公司都会使用到.Redis相关的问题可以说是面试必问的,下面我从个人当面试官的经验,总结几个必须要掌握的知识点. 介绍:Redi ...

  2. PHP返回32位与16位的md5加密值

    字符串“123456”,经过md5算法加密之后是 32位: e10adc3949ba59abbe56e057f20f883e16位: 49ba59abbe56e057 PHP自带的 md5() 函数, ...

  3. 玲珑oj 1028 贪心

    http://www.ifrog.cc/acm/problem/1028 很有趣的一道题,求从n个数里挑出不同的两个,使得他俩'|','&','^'后的值尽量大,求这个最大的结果. 求最大的异 ...

  4. 020——VUE中变异方法push的留言版实例讲解

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  5. 【2018 “百度之星”程序设计大赛 - 初赛(B)-1004】p1m2(迷之二分)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6383 题目就是让你求一个整数数组,在进行任意元素 + 1. - 2 操作后,请问在所有可能达到的稳定数 ...

  6. C# 常用时间戳处理方法

    C# 常用时间戳处理方法 /// <summary> /// 时间戳转为C#格式时间 /// </summary> /// <param name="timeS ...

  7. hdu 6059 Kanade's trio(字典树)

    Kanade's trio Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 524288/524288 K (Java/Others)T ...

  8. Easyui datagrid自定义排序

    做项目遇到个关于排序问题,想着在前端排序,正好Easyui有这个功能,所以就拿来用了一下,因为跟官网的Demo不太一样,所以总结一下: 首先这一列是要排序的列(当然,在生产环境,这一列是隐藏的,在开发 ...

  9. set类型以及其操作

    sets类型 sets类型以及操作Set是无序集合,它是string类型的无序集合.set是通过hash table实现的,添加.删除和查找的复杂度都是0(1).对集合我们可以取并集.交集.差集.通过 ...

  10. C++面向对象高级编程(七)point-like classes和function-like classes

    技术在于交流.沟通,转载请注明出处并保持作品的完整性. 1.pointer-like class 类设计成指针那样,可以当做指针来用,指针有两个常用操作符(*和->),所以我们必须重载这两个操作 ...