LeetCode 2480: Form a Chemical Bond
Problem Description
Explanation:
To solve this problem, we can iterate through the given chemical formula and count the number of atoms for each element. We need to form a chemical bond by combining the elements in a specific order based on their counts. We will maintain a hashmap to store the element counts and then generate the chemical bond string accordingly.
Algorithm:
- Initialize an empty hashmap
elementCounts
to store the counts of each element. - Iterate through the chemical formula and update the counts of each element in the
elementCounts
hashmap. - Initialize an empty string
chemicalBond
to store the final chemical bond. - Iterate through the elements in a specific order (e.g., alphabetical order) and append the element name and its count to the
chemicalBond
string. - Return the
chemicalBond
string as the result.
Time Complexity:
The time complexity of this algorithm is O(n), where n is the length of the chemical formula string.
Space Complexity:
The space complexity of this algorithm is O(m), where m is the number of unique elements in the chemical formula.
:
Solutions
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public String formChemicalBond(String formula) {
Map<Character, Integer> elementCounts = new HashMap<>();
for (char c : formula.toCharArray()) {
elementCounts.put(c, elementCounts.getOrDefault(c, 0) + 1);
}
StringBuilder chemicalBond = new StringBuilder();
Map<Character, Integer> sortedElementCounts = new TreeMap<>(elementCounts);
for (Map.Entry<Character, Integer> entry : sortedElementCounts.entrySet()) {
chemicalBond.append(entry.getKey()).append(entry.getValue());
}
return chemicalBond.toString();
}
Loading editor...