Simple Java Code ☠️
Code\n\nclass Solution {\n    public String countOfAtoms(String formula) {\n        int n = formula.length(),va=1;\n        TreeMap<String,Integer> map = new Tr
# Code\n```\nclass Solution {\n    public String countOfAtoms(String formula) {\n        int n = formula.length(),va=1;\n        TreeMap<String,Integer> map = new TreeMap<>();\n        ArrayList<Integer> list = new ArrayList<Integer>();\n        for(int i=0;i<n;i++){\n            String str="";\n            int v=1;\n            if(Character.isUpperCase(formula.charAt(i))){\n                str+=formula.charAt(i);\n                while((i+1)<n && Character.isLowerCase(formula.charAt(i+1))){\n                    str+=formula.charAt(i+1);\n                    i++;\n                }\n                int sum=0;\n                while((i+1)<n &&Character.isDigit(formula.charAt(i+1))){\n                    int a=Character.getNumericValue(formula.charAt(i+1));\n                    sum = (sum*10)+a;\n                    i++;\n                }\n                if(sum>0){\n                    v=sum;\n                }\n                if(va>0){\n                    v*=va;\n                }\n                if(map.isEmpty() || !map.containsKey(str)){\n                    map.put(str,v);\n                }\n                else{\n                    map.put(str,map.get(str)+v);\n                }\n            }\n            else if(formula.charAt(i)==\'(\'){\n                int x = help(formula,i+1);\n                if(x==0){\n                    x=1;\n                }\n                va*=x;\n                list.add(x);\n            }\n            else if(formula.charAt(i)==\')\'){\n                va/=(list.get(list.size()-1));\n                list.remove(list.size()-1);\n            }\n        }\n\n        String res = "";\n        for (Map.Entry<String, Integer> entry:map.entrySet()) {\n            if(entry.getValue()==1){\n                res+=entry.getKey();\n            }\n            else{\n                res+=(entry.getKey()+entry.getValue());\n            }\n        }\n        return res;\n    }\n    public int help(String formula,int st){\n        int sum=0,c=0;\n        for(int i=st;i<formula.length();i++){\n            if(formula.charAt(i)==\'(\'){\n                c++;\n            }\n            else if(formula.charAt(i)==\')\'){\n                if(c==0){\n                    while(i+1<formula.length() && Character.isDigit(formula.charAt(i+1))){\n                        int a = Character.getNumericValue(formula.charAt(i+1));\n                        sum=(sum*10)+a;\n                        i++;\n                    }\n                    break;\n                }\n                else{\n                    c--;\n                }\n            }\n        }\n        return sum;\n    }\n}\n```\n\n\n\n### Explanation \n\n1. **Initialization**:\n   - `n`: Length of the input formula.\n   - `va`: Variable to keep track of the current multiplier due to nested parentheses.\n   - `map`: `TreeMap` to store atoms and their counts in sorted order.\n   - `list`: `ArrayList` to store multipliers from nested parentheses.\n\n2. **Iterating through the Formula**:\n   - The method iterates through each character of the `formula` string using a `for` loop.\n\n3. **Processing Atoms**:\n   - **Uppercase Letter Handling**:\n     - If the character is uppercase (`Character.isUpperCase(formula.charAt(i))`), it starts a new atom.\n     - It builds the atom name (`str`) by appending lowercase letters that follow (`while` loop).\n     - It then reads digits to determine the count of this atom (`while` loop).\n     - If a digit sequence is found (`sum > 0`), `v` (count of current atom) is updated.\n     - `va` (multiplier due to nested parentheses) is applied to `v`.\n     - The atom and its count (`v`) are stored in the `map`.\n\n   - **Parentheses Handling**:\n     - **Opening Parenthesis `(`**:\n       - Calls the `help` method to recursively calculate the multiplier (`x`) due to nested parentheses.\n       - Updates `va` by multiplying it with `x`.\n       - Adds `x` to the `list` to keep track of nested multipliers.\n\n     - **Closing Parenthesis `)`**:\n       - Retrieves the last multiplier from `list` (`list.get(list.size()-1)`).\n       - Divides `va` by this multiplier to revert to the previous multiplier level.\n       - Removes the last multiplier from `list`.\n\n4. **Building the Result**:\n   - After iterating through the formula, constructs the result string (`res`) by iterating through the `map`.\n   - For each atom in the `map`:\n     - If the count (`entry.getValue()`) is `1`, only appends the atom name (`entry.getKey()`).\n     - If the count is greater than `1`, appends the atom name followed by its count (`entry.getKey() + entry.getValue()`).\n\n5. **Returning the Result**:\n   - Returns the constructed result string `res`.\n\n### Explanation of `help` Method:\n\n1. **Purpose**:\n   - The `help` method is used to calculate the multiplier due to nested parentheses starting from a given index (`st`) in the `formula`.\n\n2. **Parameters**:\n   - `formula`: The input chemical formula string.\n   - `st`: Starting index in the `formula` where the nested parentheses start.\n\n3. **Logic**:\n   - Initializes `sum` to accumulate the numeric value (multiplier).\n   - `c` counts nested opening parentheses as it iterates through the `formula`.\n   - Increments `c` for `(` and decrements for `)`.\n   - When `c` reaches `0` (indicating the closing of the initial nested parentheses block), it reads subsequent digits to determine the multiplier (`sum`).\n\n4. **Returns**:\n   - Returns `sum`, which is the multiplier due to the nested parentheses block.\n\n\nConsider the chemical formula `"K4(ON(SO3)2)2"`.\n\n1. **Initialization**:\n   - `formula = "K4(ON(SO3)2)2"`\n   - `n = 14` (length of `formula`)\n   - `va = 1` (a multiplier for counting nested parentheses)\n\n2. **Data Structures**:\n   - `TreeMap<String, Integer> map`: This will store each atom\'s count.\n   - `ArrayList<Integer> list`: This will track multipliers due to parentheses.\n\n3. **Processing the Formula**:\n   - **Loop through each character in `formula`**:\n     - Start with `"K"`:\n       - Add `"K"` to `str`.\n       - Since `"K"` has no lowercase letters following it, move on.\n       - `"K"` has a count of `4`, so `v = 4`.\n       - Multiply `v` by `va`, which is `1` initially, so `v` remains `4`.\n       - Add `"K"` with count `4` to `map`.\n     - Continue with `"("`:\n       - Call `help(formula, 2)` to handle the substring `"ON(SO3)2)2"`.\n         - Inside `help()`:\n           - Loop through characters starting from index `2` (after `"("`):\n             - Encounters `"O"`: Add `"O"` to `str`.\n             - No digits following `"O"`, so `v = 1`.\n             - Add `"O"` with count `1` to `map`.\n             - Encounters `"N"`: Add `"N"` to `str`.\n             - No digits following `"N"`, so `v = 1`.\n             - Add `"N"` with count `1` to `map`.\n             - Encounters `"("` again: Call `help(formula, 5)` to handle `"SO3)2"`.\n               - Inside nested `help()`:\n                 - Loop through characters starting from index `5` (after `"("`):\n                   - Encounters `"S"`: Add `"S"` to `str`.\n                   - Encounters `"O"`: Add `"O"` to `str`.\n                   - Encounters `"3"`: Parse `"3"` as a number, so `v = 3`.\n                   - Add `"SO3"` with count `3` to `map`.\n                 - Loop ends, returns `3` (as `sum`), representing the multiplier for `"SO3"`.\n               - Back to `"("` loop in `help()`, update `va` to `2` (from `"SO3)2"`).\n               - Continue loop in `help()`, encounters `"2"` and ends, returns `2` (as `sum`), representing the multiplier for `"ON"`.\n             - Update `va` to `2` from previous call to `help()`.\n         - Back to main loop, continue with `"2"`, ignore as it\'s part of the multiplier.\n       - End of `"("` processing in main loop, update `va /= 2` (undo multiplier).\n\n4. **Final Computation**:\n   - After processing, `map` contains:\n     - `"K"`: `4`\n     - `"O"`: `4`\n     - `"N"`: `2`\n     - `"S"`: `6`\n   - Sort and format `map` entries into `res` as `"K4N2O4S6"`.\n   - Return `"K4N2O4S6"`.\n\n\n\n\n### Complexity:\n- **Time Complexity**: O(n) : The algorithm traverses each character of the formula once, making it `O(n)`, where `n` is the length of the formula.\n- **Space Complexity**: O(n) : Additional space is used for the `map` and `list`, which could at most store each unique atom name and its count. This makes the space complexity `O(n)` in the worst case.\n\n\n
['Hash Table', 'String', 'Sorting', 'Java']