MCPcopy Index your code
hub / github.com/Tiwarishashwat/InterviewCodes / countOfAtoms

Method countOfAtoms

numberOfAtoms.java:2–71  ·  view source on GitHub ↗
(String formula)

Source from the content-addressed store, hash-verified

1class Solution {
2 public String countOfAtoms(String formula) {
3 int n = formula.length();
4 Stack<HashMap<String,Integer>> stack = new Stack<>();
5 stack.push(new HashMap<String,Integer>());
6 int index=0;
7 // O(N) + O(K)
8 //O(N)*(N)
9 while(index<n){
10 char ch = formula.charAt(index);
11 if(ch == '('){
12 stack.push(new HashMap<String,Integer>());
13 index++;
14 }else if(ch == ')'){
15 HashMap<String,Integer> curMap = stack.pop();
16 index++; //move to the next char
17 //find the multiplier
18 StringBuilder multiplier = new StringBuilder();
19 while(index < n && Character.isDigit(formula.charAt(index))){
20 multiplier.append(formula.charAt(index));
21 index++;
22 }
23 //multiply the count - ()n
24 if(multiplier.length()>0){
25 int m = Integer.parseInt(multiplier.toString());
26 for(String atom : curMap.keySet()){
27 curMap.put(atom, curMap.get(atom) * m);
28 }
29 }
30 //insert popped map elements into stack top
31 for(String atom : curMap.keySet()){
32 stack.peek().put(
33 atom,
34 stack.peek().getOrDefault(atom,0)+curMap.get(atom)
35 );
36 }
37
38 }else{ //Atom name and count
39 // take the uppercase letter
40 StringBuilder atomName = new StringBuilder();
41 atomName.append(ch);
42 index++;
43 //collect all lowercase letters
44 while(index < n && Character.isLowerCase(formula.charAt(index))){
45 atomName.append(formula.charAt(index));
46 index++;
47 }
48 StringBuilder count = new StringBuilder();
49 while(index < n && Character.isDigit(formula.charAt(index))){
50 count.append(formula.charAt(index));
51 index++;
52 }
53 int c = (count.length()>0)?Integer.parseInt(count.toString()):1;
54 stack.peek().put(
55 atomName.toString(),
56 stack.peek().getOrDefault(atomName.toString(),0)+c
57 );
58 }
59 }
60 // 2K

Callers

nothing calls this directly

Calls 2

pushMethod · 0.80
popMethod · 0.80

Tested by

no test coverage detected