EDIT Updated to take into account order. Thanks @JakeStanger!
2nd EDIT Updated to reflect new state when molecule ends |
I used regex to split on | , since from this String we know that a new molecule begins after | . I used a Hashmap to track the number of molecules of each type. In the end, I repeated each value in the Hashmap and added to the String result depending on whether it was a single molecule or not. Hooray!
public static String factorise(String input) { String result = ""; Map<String, Integer> molecules = new LinkedHashMap<>(); String[] res = input.split("\\|"); for (String t : res) { //Check if we already have this element in our map if (!molecules.containsKey(t)) { //If not then add it and set the count to 1 molecules.put(t, 1); } else { //If we do then update the count by 1 molecules.put(t, molecules.get(t) + 1); } } //Iterate through each molecule for (String key : molecules.keySet()) { if (molecules.get(key) == 1) { //If the count is only at one, then we just need to append it. result += key; } else { //Otherwise, we need the parentheces and the number of repetitions followed after result = result + "(" + key + ")" + molecules.get(key); } } return result; }
Launch
System.out.println(factorise("C6|H2|NO2|NO2|NO2|CH3|OH|OH")); System.out.println(factorise("HO|HO"));
It is installed at startup:
mileage:
C6H2 (NO2) 3CH3 (OH) 2
(HO) 2
BUILD SUCCESSFUL (total time: 0 seconds)
source share