[Java] Easy no stack of Map
We essentially start from the back. Each time we encounter a number we add it to the stack. We can clearly see that going backwards, a number will always be pre
We essentially start from the back. Each time we encounter a number we add it to the stack. We can clearly see that going backwards, a number will always be preceeded by either `)` or `element`. So in the same loop we first parse the number followed by the element/bracket. If a number is not seen, we take the default 1 as the number.\n\nWe maintain the stack with the multipliers encountered and keep a `multiplier` variable to store the product. Upon poping the stack, we divide by this popped number.\n\nEverytime we encounter a `(`, we pop the stack. We again pop the stack after each element is processed.\n\nWe also use StringBuilder to optimize.\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```
['Java']