[LeetCode] 726. 原子的數量
阿新 • • 發佈:2021-07-06
大模擬。。。煩這種題
遇到括號匹配的題目,用棧就對了。此題需要棧+Map
沒啥難度,寫了半天,Debug幾個用例後,1A過了
class Solution { class Atom { String s; int cnt = 1; Atom(String s, int cnt) { this.s = s; if (cnt == 0) cnt = 1; this.cnt = cnt; } } public String countOfAtoms(String formula) { Stack<Atom> stack = new Stack<>(); Map<String, Atom> map = new HashMap<>(); int n = formula.length(); Atom b = new Atom("(", 0); String tmp = ""; int cnt = 0; for (int i = 0; i < n; i++) { char c = formula.charAt(i); if (c >= 'a' && c <= 'z') { tmp += c; continue; } if (c >= '0' && c <= '9') { cnt *= 10; cnt += c - '0'; continue; } if (c >= 'A' && c <= 'Z') { if ("".equals(tmp)) { tmp += c; } else { if (tmp.length() > 0) stack.push(new Atom(tmp, cnt)); tmp = "" + c; cnt = 0; } continue; } if (c == '(') { if (tmp.length() > 0) stack.push(new Atom(tmp, cnt)); tmp = ""; cnt = 0; stack.push(b); continue; } if (c == ')') { if (tmp.length() > 0) stack.push(new Atom(tmp, cnt)); tmp = ""; cnt = 0; i++; while (i < n) { c = formula.charAt(i); if (c >= '0' && c <= '9') { cnt *= 10; cnt += c - '0'; } else { break; } i++; } i--; if (cnt == 0) cnt = 1; List<Atom> list = new ArrayList<>(); while (true) { Atom pop = stack.pop(); if (pop.s.equals("(")) break; pop.cnt *= cnt; list.add(pop); } stack.addAll(list); cnt = 0; } } if (tmp.length() > 0) stack.push(new Atom(tmp, cnt)); List<Atom> ans = new ArrayList<>(stack); for (Atom an : ans) { if (map.containsKey(an.s)) { map.get(an.s).cnt += an.cnt; } else { map.put(an.s, an); } } Stream<Atom> sorted = map.values().stream().sorted(Comparator.comparing(o -> o.s)); StringBuilder ret = new StringBuilder(); sorted.forEach(an->{ ret.append(an.s); if (an.cnt > 1) ret.append(an.cnt); }); return ret.toString(); } }