LeetCode 726: Number of Atoms Solution
Master LeetCode problem 726 (Number of Atoms), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
726. Number of Atoms
Problem Explanation
Explanation
-
Algorithmic Idea:
- We will use a stack to keep track of the count of atoms at each level of nested parentheses.
- We will iterate through the input formula character by character and update the count of atoms accordingly.
- At each step, we will handle four cases: uppercase letter (start of an atom), lowercase letter (part of an atom), digit (multiplier for the atom count), and parentheses.
- After processing the entire formula, we will construct the final count of atoms by multiplying the counts at each level of parentheses.
- Finally, we will sort the atom counts and construct the output string.
-
Time Complexity: O(n) where n is the length of the input formula.
-
Space Complexity: O(n) for the stack and output map.
Solution Code
class Solution {
public String countOfAtoms(String formula) {
Stack<Map<String, Integer>> stack = new Stack<>();
Map<String, Integer> count = new TreeMap<>();
int i = 0, n = formula.length();
while (i < n) {
char c = formula.charAt(i);
i++;
if (c == '(') {
stack.push(count);
count = new TreeMap<>();
} else if (c == ')') {
int val = 0;
while (i < n && Character.isDigit(formula.charAt(i))) {
val = val * 10 + formula.charAt(i) - '0';
i++;
}
if (val == 0) val = 1;
if (!stack.isEmpty()) {
Map<String, Integer> tmp = count;
count = stack.pop();
for (String key : tmp.keySet()) {
count.put(key, count.getOrDefault(key, 0) + tmp.get(key) * val);
}
}
} else {
int start = i - 1;
while (i < n && Character.isLowerCase(formula.charAt(i))) i++;
String atom = formula.substring(start, i);
int val = 0;
while (i < n && Character.isDigit(formula.charAt(i))) {
val = val * 10 + formula.charAt(i) - '0';
i++;
}
if (val == 0) val = 1;
count.put(atom, count.getOrDefault(atom, 0) + val);
}
}
StringBuilder sb = new StringBuilder();
for (String key : count.keySet()) {
sb.append(key);
if (count.get(key) > 1) sb.append(count.get(key));
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 726 (Number of Atoms)?
This page provides optimized solutions for LeetCode problem 726 (Number of Atoms) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 726 (Number of Atoms)?
The time complexity for LeetCode 726 (Number of Atoms) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 726 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 726 in Java, C++, or Python.