Skip to content

Commit 6ceab9a

Browse files
authored
Update README.md
1 parent 772a22d commit 6ceab9a

File tree

1 file changed

+43
-1
lines changed
  • solution/0700-0799/0726.Number of Atoms

1 file changed

+43
-1
lines changed

solution/0700-0799/0726.Number of Atoms/README.md

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,49 @@ tags:
9898
#### Java
9999

100100
```java
101-
101+
class Solution {
102+
public String countOfAtoms(String formula) {
103+
Map<String, Integer> map = new HashMap<>();
104+
int[] stack = new int[1000];
105+
int top = 0, multiplier = 1, freq = 0;
106+
char[] c = formula.toCharArray();
107+
for(int i = c.length - 1; i >= 0; i--) {
108+
if(c[i] >= 'a' && c[i] <= 'z') {
109+
int end = i--;
110+
while(i >= 0 && c[i] >= 'a' && c[i] <= 'z') i--;
111+
String key = new String(c, i, end - i + 1);
112+
map.put(key, map.getOrDefault(key, 0) + Math.max(freq, 1) * multiplier);
113+
freq = 0;
114+
} else if(c[i] >= 'A' && c[i] <= 'Z') {
115+
String key = new String(c, i, 1);
116+
map.put(key, map.getOrDefault(key, 0) + Math.max(freq, 1) * multiplier);
117+
freq = 0;
118+
} else if(c[i] >= '0' && c[i] <= '9') {
119+
freq = c[i] - '0';
120+
int p = 10;
121+
while(i-1 >= 0 && c[i-1] >= '0' && c[i-1] <= '9') {
122+
freq += p * (c[--i] - '0');
123+
p *= 10;
124+
}
125+
} else if(c[i] == ')') {
126+
stack[top++] = multiplier;
127+
multiplier *= Math.max(freq, 1);
128+
freq = 0;
129+
} else {
130+
multiplier = stack[--top];
131+
}
132+
}
133+
List<String> keys = new ArrayList<>(map.keySet());
134+
Collections.sort(keys);
135+
StringBuilder sb = new StringBuilder();
136+
for(String key: keys) {
137+
sb.append(key);
138+
int f = map.get(key);
139+
if(f > 1) sb.append(f);
140+
}
141+
return sb.toString();
142+
}
143+
}
102144
```
103145

104146
#### C++

0 commit comments

Comments
 (0)