Java Solution using Stack and Map
\nclass Solution {\n    public String countOfAtoms(String formula) {\n        Stack<Map<String,Integer>> stack= new Stack<>();\n        Map<String,Integer> map=
```\nclass Solution {\n    public String countOfAtoms(String formula) {\n        Stack<Map<String,Integer>> stack= new Stack<>();\n        Map<String,Integer> map= new HashMap<>();\n        int i=0,n=formula.length();\n        while(i<n){\n            char c=formula.charAt(i);i++;\n            if(c=='('){\n                stack.push(map);\n                map=new HashMap<>();\n            }\n            else if(c==')'){\n                int val=0;\n                while(i<n && Character.isDigit(formula.charAt(i)))\n                    val=val*10+formula.charAt(i++)-'0';\n\n                if(val==0) val=1;\n                if(!stack.isEmpty()){\n                Map<String,Integer> temp= map;\n                map=stack.pop();\n                    for(String key: temp.keySet())\n                        map.put(key,map.getOrDefault(key,0)+temp.get(key)*val);\n                }\n            }\n            else{\n                int start=i-1;\n                while(i<n && Character.isLowerCase(formula.charAt(i))){\n                 i++;\n                }\n                String s= formula.substring(start,i);\n                int val=0;\n                while(i<n && Character.isDigit(formula.charAt(i))) val=val*10+ formula.charAt(i++)-'0';\n                if(val==0) val=1;\n                map.put(s,map.getOrDefault(s,0)+val);\n            }\n        }\n        StringBuilder sb= new StringBuilder();\n        List<String> list= new ArrayList<>(map.keySet());\n        Collections.sort(list);\n        for(String key: list){ \n            sb.append(key);\n          if(map.get(key)>1) sb.append(map.get(key));\n                                    }\n        return sb.toString();\n    }\n}\n\n```
[]