LWC 58:726. Number of Atoms

LWC 58:726. Number of Atoms

传送门:726. Number of Atoms

Problem:

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.

思路: 递归真的是个好东西,思路比较暴力,如果没有遇到括号,则按照传统的检测字符和数字进行更新即可。如果检测到括号,则先得到括号内的元素和个数的映射,接着乘上大括号外的第一个num,再将第三部分的答案组合进来即可。

比如:

H2O2(SO2)23(OH)23

上述字符串可以组成三部分

lf = "H2O2"
mid = "(SO2)23" 
rt = "(OH)23"

只有mid需要特殊处理,把{s = 1 * 32, O = 2 * 23 = 46}
而一旦解决mid,则rt跟着被解决,lf在之前就被解决了,具体看代码,不解释了。

代码如下:

    public String countOfAtoms(String formula) {
        Map<String, Integer> map = go(formula.toCharArray(), 0, formula.length() - 1);

        StringBuilder sb = new StringBuilder();
        List<String> set = new ArrayList<>(map.keySet());
        Collections.sort(set);
        for (String key : set) {
            sb.append(key);
            if (map.get(key) > 1) {
                sb.append(map.get(key));
            }
        }
        return sb.toString();
    }

    public Map<String, Integer> go(char[] cs, int s, int e){
        if (s > e) return new HashMap<>();

        Map<String, Integer> ans = new HashMap<>();
        int idx = new String(cs).substring(s, e + 1).indexOf("(");
        if (idx != -1) idx += s;
        if (idx == -1) {

            StringBuilder sb = new StringBuilder();
            for (int i = s; i <= e;) {
                if (Character.isUpperCase(cs[i])) {
                    sb.append(cs[i]);
                    i ++;

                    if (i <= e && Character.isUpperCase(cs[i])) {
                        String ele = sb.toString();
                        if (!ans.containsKey(ele)) {
                            ans.put(ele, 1);
                        }
                        else {
                            ans.put(ele, ans.get(ele) + 1);
                        }
                        sb = new StringBuilder();
                    }
                    else if (i <= e && Character.isLowerCase(cs[i])) {
                        while (i <= e && Character.isLowerCase(cs[i])) {
                            sb.append(cs[i]);
                            i ++;
                        }
                        if (i <= e && !Character.isDigit(cs[i])){
                            String ele = sb.toString();
                            if (!ans.containsKey(ele)) {
                                ans.put(ele, 1);
                            }
                            else {
                                ans.put(ele, ans.get(ele) + 1);
                            }
                            sb = new StringBuilder();
                        }
                    }

                    if (i <= e && Character.isDigit(cs[i])) {
                        int num = 0;
                        while (i <= e && Character.isDigit(cs[i])) {
                            num = num * 10 + cs[i] - '0';
                            i ++;
                        }

                        String ele = sb.toString();
                        if (!ans.containsKey(ele)) {
                            ans.put(ele, num);
                        }
                        else {
                            ans.put(ele, ans.get(ele) + num);
                        }

                        sb = new StringBuilder();
                    }
                }
            }

            String ele = sb.toString();
            if (!ele.isEmpty()) {
                if (!ans.containsKey(ele)) {
                    ans.put(ele, 1);
                }
                else {
                    ans.put(ele, ans.get(ele) + 1);
                }
            }
            return ans;
        }
        else {
            Map<String, Integer> lf = go(cs, s, idx - 1);

            StringBuilder sb = new StringBuilder();
            int p = 1;
            Map<String, Integer> include;
            int num = 0;
            int j = -1;
            for (int i = idx + 1; i <= e; ++i) {
                sb.append(cs[i]);
                if (cs[i] == '(') {
                    p ++;
                }
                else if (cs[i] == ')') {
                    p --;
                    if (p == 0) {
                        j = i + 1;
                        while (j <= e && Character.isDigit(cs[j])) {
                            num = num * 10 + cs[j] - '0';
                            j ++;
                        }
                        break;
                    }
                }
            }
            String ele = sb.toString().substring(0, sb.length() - 1);
            include = go(ele.toCharArray(), 0, ele.length() - 1);

            for (String key : include.keySet()) {
                include.put(key, include.get(key) * num);
            }

            Map<String, Integer> rt = go(cs, j, e);

            add(ans, lf);
            add(ans, include);
            add(ans, rt);

            return ans;
        }
    }

    public void add(Map<String, Integer> ans, Map<String, Integer> tmp) {
        for (String key : tmp.keySet()) {
            if (!ans.containsKey(key)) {
                ans.put(key, tmp.get(key));
            }
            else {
                ans.put(key, ans.get(key) + tmp.get(key));
            }
        }
    }

注意一些细节: 首先,对于字符串”H2O2BeBe49”这样的formula,第一次一定会遇到大写字符,接着把大写字母后的小写字母全部给append上,这样只会遇到两种情况:下一个字符为数字,或者下一个字符为大写字符。

如过遇到字符,则计算num,如果遇到大写字符,则formula省略了1,需要加上。

代码更新如下:

    public String countOfAtoms(String formula) {
        Map<String, Integer> map = go(formula.toCharArray(), 0, formula.length() - 1);

        StringBuilder sb = new StringBuilder();
        List<String> set = new ArrayList<>(map.keySet());
        Collections.sort(set);
        for (String key : set) {
            sb.append(key);
            if (map.get(key) > 1) {
                sb.append(map.get(key));
            }
        }
        return sb.toString();
    }

    public Map<String, Integer> go(char[] cs, int s, int e){
        if (s > e) return new HashMap<>();

        Map<String, Integer> ans = new HashMap<>();
        int idx = new String(cs).substring(s, e + 1).indexOf("(");
        if (idx != -1) idx += s;
        if (idx == -1) {

            StringBuilder sb = new StringBuilder();
            for (int i = s; i <= e;) {
                if (Character.isUpperCase(cs[i])) {
                    sb.append(cs[i]);
                    i ++;

                    while (i <= e && Character.isLowerCase(cs[i])){
                        sb.append(cs[i]);
                        i ++;
                    }

                    if (i <= e && !Character.isDigit(cs[i])){
                        String ele = sb.toString();
                        if (!ans.containsKey(ele)) {
                            ans.put(ele, 1);
                        }
                        else {
                            ans.put(ele, ans.get(ele) + 1);
                        }
                        sb = new StringBuilder();
                    }
                    else if (i <= e && Character.isDigit(cs[i])) {

                        int num = 0;
                        while (i <= e && Character.isDigit(cs[i])) {
                            num = num * 10 + cs[i] - '0';
                            i ++;
                        }

                        String ele = sb.toString();
                        if (!ans.containsKey(ele)) {
                            ans.put(ele, num);
                        }
                        else {
                            ans.put(ele, ans.get(ele) + num);
                        }

                        sb = new StringBuilder();
                    }
                }
            }

            String ele = sb.toString();
            if (!ele.isEmpty()) {
                if (!ans.containsKey(ele)) {
                    ans.put(ele, 1);
                }
                else {
                    ans.put(ele, ans.get(ele) + 1);
                }
            }
            return ans;
        }
        else {
            Map<String, Integer> lf = go(cs, s, idx - 1);

            StringBuilder sb = new StringBuilder();
            int p = 1;
            Map<String, Integer> include;
            int num = 0;
            int j = -1;
            for (int i = idx + 1; i <= e; ++i) {
                sb.append(cs[i]);
                if (cs[i] == '(') {
                    p ++;
                }
                else if (cs[i] == ')') {
                    p --;
                    if (p == 0) {
                        j = i + 1;
                        while (j <= e && Character.isDigit(cs[j])) {
                            num = num * 10 + cs[j] - '0';
                            j ++;
                        }
                        break;
                    }
                }
            }
            String ele = sb.toString().substring(0, sb.length() - 1);
            include = go(ele.toCharArray(), 0, ele.length() - 1);

            for (String key : include.keySet()) {
                include.put(key, include.get(key) * num);
            }

            Map<String, Integer> rt = go(cs, j, e);
            add(ans, lf);
            add(ans, include);
            add(ans, rt);

            return ans;
        }
    }

    public void add(Map<String, Integer> ans, Map<String, Integer> tmp) {
        for (String key : tmp.keySet()) {
            if (!ans.containsKey(key)) {
                ans.put(key, tmp.get(key));
            }
            else {
                ans.put(key, ans.get(key) + tmp.get(key));
            }
        }
    }     

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏后端沉思录

自定义参数解析器

开发中,app端给服务端会传基础参数、其他参数,一般基础参数app端都会传给服务端,其他参数则是根据不同接口传不同参数。若以表单的形式提交的数据:

1143
来自专栏包子铺里聊IT

How to design and implement a blocking queue?

Question: Blocking queue related question often gets asked from Google, LinkedI...

32212
来自专栏机器学习入门

LWC 51:681. Next Closest Time

LWC 51:681. Next Closest Time 传送门:681. Next Closest Time Problem: Given a time ...

2366
来自专栏Android干货

Java数据解析---JSON

3937
来自专栏小樱的经验随笔

【经验总结】Java在ACM算法竞赛编程中易错点

一、Java之ACM易错点 1. 类名称必须采用public class Main方式命名 2. 在有些OJ系统上,即便是输出的末尾多了一个“ ”,程序可能会输...

2714
来自专栏SpringBoot

Java 进制转换工具类

571
来自专栏机器学习入门

LWC 59:731. My Calendar II

LWC 59:731. My Calendar II 传送门:729. My Calendar II Problem: Implement a MyCalen...

2447
来自专栏向治洪

[置顶] 浅谈我为什么选择用Retrofit作为我的网络请求框架

比较AsyncTask、Volley、Retrofit三者的请求时间 使用 单次请求 7个请求 25个请求 AsyncTask 94...

1955
来自专栏偏前端工程师的驿站

Java魔法堂:枚举类型详解

一、前言                                   Java的枚举类型相对C#来说具有更灵活可配置性,Java的枚举类型可以携带更多的...

1966
来自专栏机器学习入门

POJ 刷题系列:1503 Integer Inquiry

POJ 刷题系列:1503 Integer Inquiry 传送门:POJ 1503 Integer Inquiry 题意: 实现VeryLongIntege...

1957

扫码关注云+社区