-
Notifications
You must be signed in to change notification settings - Fork 0
/
no. of atom.cpp
66 lines (64 loc) · 1.91 KB
/
no. of atom.cpp
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
55
56
57
58
59
60
61
62
63
64
65
66
class Solution {
public:
string countOfAtoms(string s) {
stack<pair<string, int>> st;
stack<int> fact;
int n = s.length(), m = 1, val = 1;
for(int i = n - 1; i >= 0; i--){
char ch = s[i];
// ch --> lowercase letter
if(ch >= 'a' && ch <= 'z'){
string element = "";
while(!(s[i] >= 'A' && s[i] <= 'Z')){
element = s[i] + element;
i--;
}
element = s[i] + element;
int freq = m*val;
st.push({element, freq});
val = 1;
}
// ch --> uppercase letter
else if(s[i] >= 'A' && s[i] <= 'Z'){
string element = "";
element += s[i];
int freq = m*val;
st.push({element, freq});
val = 1;
}
else if(ch == ')'){
fact.push(val);
m *= val;
val = 1;
}
else if(ch == '('){
m /= fact.top();
fact.pop();
}
else{
string num = "";
while(s[i] <= '9' && s[i] >= '0'){
num = s[i] + num;
i--;
}
i++;
val = stoi(num);
}
}
map<string, int> mp;
while(! st.empty()){
auto it = st.top(); st.pop();
string str = it.first;
int freq = it.second;
mp[str] += freq;
}
string res = "";
for(auto it : mp){
string ele = it.first;
string freq = "";
if(it.second != 1) freq += to_string(it.second);
res += ele + freq;
}
return res;
}
};