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.
huahua:http://zxi.mytechroad.com/blog/string/leetcode-726-number-of-atoms/ grandyang: https://www.cnblogs.com/grandyang/p/8667239.html
思路:
首先举个栗子:K4(ON(SO3)2)2,先提取K, 随后发现K的个数是4,记录下来。此时遇到了‘(’,开始递归求解子问题ON(SO3)2。同样的,先记录O, N 各有一个,再次遇到‘(’,递归求解SO3,得到{S: 1, O: 3}。这时遍历遇到了’)’,是返回到上层函数的时候,我们返回的应该是当前层所累计的这个{S: 1, O: 3}的map,这样在返回上层后,我们继续读取到2这个数字,将{S: 1, O: 3} * 2 变成{S: 2, O: 6},并与当前层之前统计的{N: 1, O: 1}合并,再次遇到‘)’,继续放回{N: 1, O: 7, S: 1},读取数字2,{N: 1, O: 7, S: 1}* 2 变成 {N: 2, O: 14, S: 2},与{K: 4}合并,得到 {K: 1, N: 2, O: 14, S: 2} 即为最终结果。那么这个过程中一共有如下几个子问题:在当前层中读取元素getElement, 读取数字getNumber,遇到‘(’发起递归,遇到‘)’返回map。其中前两个子问题我们可以拆解出两个函数,再和后两个一起放进主函数中处理。这个过程中要来回传递一个reference来标记当前指针指向的坐标每一个子过程都有义务维护这个指针。