Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/726.html

726. Number of Atoms (Hard)

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.
  • Related Topics:
    Hash Table, Stack, Recursion

    Similar Questions:

    Solution 1.

    • class Solution {
          public String countOfAtoms(String formula) {
              StringBuffer sb = new StringBuffer();
              sb.append(formula.charAt(0));
              char prevC = formula.charAt(0);
              int length = formula.length();
              for (int i = 1; i < length; i++) {
                  char c = formula.charAt(i);
                  boolean flag = Character.isLowerCase(c) || Character.isDigit(c) && Character.isDigit(prevC);
                  if (!flag)
                      sb.append(' ');
                  sb.append(c);
                  prevC = c;
              }
              String[] array = sb.toString().split(" ");
              Stack<String> stack = new Stack<String>();
              int arrayLength = array.length;
              for (int i = 0; i < arrayLength; i++) {
                  String str = array[i];
                  if (str.equals(")")) {
                      if (i < arrayLength - 1 && Character.isDigit(array[i + 1].charAt(0)))
                          stack.push(str);
                      else {
                          Stack<String> tempStack = new Stack<String>();
                          while (!stack.peek().equals("("))
                              tempStack.push(stack.pop());
                          stack.pop();
                          while (!tempStack.isEmpty())
                              stack.push(tempStack.pop());
                      }
                  } else if (Character.isDigit(str.charAt(0))) {
                      int count = Integer.parseInt(str);
                      String prev = stack.pop();
                      if (prev.equals(")")) {
                          Stack<String> tempStack = new Stack<String>();
                          while (!stack.peek().equals("(")) {
                              String element = stack.pop();
                              int index = element.indexOf(',');
                              if (index >= 0) {
                                  String atom = element.substring(0, index);
                                  int atomCount = Integer.parseInt(element.substring(index + 1)) * count;
                                  tempStack.push(atom + "," + atomCount);
                              } else
                                  tempStack.push(element + "," + str);
                          }
                          stack.pop();
                          while (!tempStack.isEmpty())
                              stack.push(tempStack.pop());
                      } else {
                          String curStr = prev + "," + str;
                          stack.push(curStr);
                      }
                  } else
                      stack.push(str);
              }
              TreeMap<String, Integer> map = new TreeMap<String, Integer>();
              while (!stack.isEmpty()) {
                  String atomCount = stack.pop();
                  int index = atomCount.indexOf(',');
                  if (index >= 0) {
                      String atom = atomCount.substring(0, index);
                      int count = Integer.parseInt(atomCount.substring(index + 1));
                      count += map.getOrDefault(atom, 0);
                      map.put(atom, count);
                  } else {
                      int count = map.getOrDefault(atomCount, 0) + 1;
                      map.put(atomCount, count);
                  }
              }
              StringBuffer output = new StringBuffer();
              Set<String> keySet = map.keySet();
              for (String atom : keySet) {
                  int count = map.get(atom);
                  output.append(atom);
                  if (count > 1)
                      output.append(count);
              }
              return output.toString();
          }
      }
      
    • // OJ: https://leetcode.com/problems/number-of-atoms/
      // Time: O(N^2)
      // Space: O(N)
      class Solution {
          int N;
          int readNum(string &s, int &i) {
              int cnt = 0;
              while (i < N && isdigit(s[i])) cnt = cnt * 10 + (s[i++] - '0');
              return cnt ? cnt : 1;
          }
          map<string, int> dfs(string &s, int &i, bool isInParens = false) {
              map<string, int> m;
              if (isInParens) ++i;
              while (i < N && s[i] != ')') {
                  if (s[i] == '(') {
                      auto mm = dfs(s, i, true);
                      for (auto &p : mm) m[p.first] += p.second;
                  } else {
                      string symbol = string(1, s[i++]);
                      while (i < N && islower(s[i])) symbol += s[i++];
                      m[symbol] += readNum(s, i);
                  }
              }
              if (isInParens) {
                  ++i;
                  int cnt = readNum(s, i);
                  for (auto &p : m) p.second *= cnt;
              }
              return m;
          }
      public:
          string countOfAtoms(string formula) {
              N = formula.size();
              int i = 0;
              auto m = dfs(formula, i);
              string ans;
              for (auto &p : m) ans += p.first + (p.second > 1 ? to_string(p.second) : "");
              return ans;
          }
      };
      
    • class Solution(object):
          def countOfAtoms(self, formula):
              """
              :type formula: str
              :rtype: str
              """
              count = self.dfs(formula)
              res = ""
              for atom, num in sorted(count.items()):
                  if num == 1:
                      res += atom
                  else:
                      res += atom + str(num)
              return res
              
          def dfs(self, formula):
              count = collections.Counter()
              if not formula: return count
              i = 0
              while i < len(formula):
                  if formula[i].isalpha(): # 首字母是英文字符
                      atom = formula[i]
                      atomNum = 0
                      # 找到这个元素所有字符
                      i += 1
                      while i < len(formula) and formula[i].isalpha() and formula[i].islower():
                          atom += formula[i]
                          i += 1
                      while i < len(formula) and formula[i].isdigit(): # 后面是否有数字
                          atomNum = 10 * atomNum + int(formula[i])
                          i += 1
                      count[atom] += 1 if atomNum == 0 else atomNum # 使用加号
                  elif formula[i] == "(": # 括号匹配
                      left = i # 左括号位置
                      parent = 1 # 统计括号个数
                      while i < len(formula) and parent != 0:
                          i += 1
                          if formula[i] == "(":
                              parent += 1
                          elif formula[i] == ")":
                              parent -= 1
                      right = i
                      atomNum = 0
                      i += 1
                      while i < len(formula) and formula[i].isdigit(): # 后面是否有数字
                          atomNum = 10 * atomNum + int(formula[i])
                          i += 1
                      innerCount = self.dfs(formula[left + 1 : right])
                      for c, n in innerCount.items():
                          count[c] += n * atomNum
              count += self.dfs(formula[i + 1 :])
              return count
      

    All Problems

    All Solutions