-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathNumber of Atoms.java
54 lines (47 loc) · 2.09 KB
/
Number of Atoms.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public String countOfAtoms(String formula) {
Deque<Integer> multiplier = new ArrayDeque<>();
Map<String, Integer> map = new HashMap<>();
int lastValue = 1;
multiplier.push(1);
// Iterate from right to left
for (int i = formula.length() - 1; i >= 0; i--) {
if (Character.isDigit(formula.charAt(i))) { // Case of a digit - Get full number and save
StringBuilder sb = new StringBuilder();
while (Character.isDigit(formula.charAt(i-1))) {
sb.append(formula.charAt(i));
i--;
}
sb.append(formula.charAt(i));
lastValue = Integer.parseInt(sb.reverse().toString());
} else if (formula.charAt(i) == ')') { // Start parenthesis - push next multiplier to stack
multiplier.push(lastValue * multiplier.peek());
lastValue = 1;
} else if (formula.charAt(i) == '(') { // End parenthesis - pop last multiplier
multiplier.pop();
} else { // Case of an element name - construct name, update count based on multiplier
StringBuilder sb = new StringBuilder();
while (Character.isLowerCase(formula.charAt(i))) {
sb.append(formula.charAt(i));
i--;
}
sb.append(formula.charAt(i));
String element = sb.reverse().toString();
map.put(element, map.getOrDefault(element, 0) + lastValue * multiplier.peek());
lastValue = 1;
}
}
// Sort map keys
List<String> elements = new ArrayList<>(map.keySet());
StringBuilder sb = new StringBuilder();
Collections.sort(elements);
// Construct output
for (String element : elements) {
sb.append(element);
if (map.get(element) > 1) {
sb.append(map.get(element));
}
}
return sb.toString();
}
}