Java Clean Solution | With Detail Explanation
Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n+k)\n Add your space complexity here, e.g. O(n) \n\n# Co
# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n+k)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    Map<String, Integer> res = new TreeMap<>();\n    Stack<Integer> stack = new Stack<>();\n    int multiplier = 1;\n    \n    public String countOfAtoms(String formula) {\n        int end = formula.length() - 1, i = formula.length() - 1;\n        \n        while (i >= 0) {\n            if (formula.charAt(i) == \'(\') {\n                multiplier /= stack.pop();\n                i--;\n                continue;\n            }\n            \n            end = i;\n            int val = 1;\n            \n            if (Character.isDigit(formula.charAt(i))) {\n                while (Character.isDigit(formula.charAt(i))) i--;\n                val = Integer.parseInt(formula.substring(i+1, end+1));\n            } \n            stack.push(val);\n            multiplier *= val;\n            \n            end = i;\n            if (Character.isLetter(formula.charAt(i))) {\n                while(Character.isLowerCase(formula.charAt(i))) i--;\n                updateMap(formula.substring(i, end+1));\n            }\n            i--;\n        }\n        \n        StringBuilder rs = new StringBuilder();\n        for (Map.Entry<String, Integer> entry : res.entrySet()) {\n            rs.append(entry.getKey());\n            if (entry.getValue() > 1) rs.append(entry.getValue());\n        }\n        return rs.toString();\n    }\n    \n    private void updateMap(String key) {\n        if (res.get(key) == null) {\n            res.put(key, multiplier);\n        } else {\n            res.put(key, multiplier + res.get(key));\n        }\n\n        multiplier /= stack.pop();\n    }\n}\n```
['Hash Table', 'Math', 'String', 'Stack', 'Sorting', 'Java']