-
Notifications
You must be signed in to change notification settings - Fork 0
/
countofAtoms.cpp
53 lines (53 loc) · 914 Bytes
/
countofAtoms.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
string countOfAtoms(string formula)
{
map<string,int> m;
map<string,int> ret;
char arr[formula.length()];
int i=0;
string temp;
formula.copy(arr,formula.length(),0);
stack<char> s;
for(int i=0;i<formula.length();++i)
{
if(arr[i]=='(')
{
int c=1;
while(c)
{
s.push(arr[i]);
if(arr[i]=='(')
++c;
else if(arr[i]==')')
--c;
}
}
else if(arr[i]>='A'&&arr[i]<='Z')
{
if(temp.length())
m[temp]+=1;
temp.clear();
temp.push_back(arr[i]);
}
else if(arr[i]>='0'&&arr[i]<='9')
{
if(temp.length())
{
m[temp]+=arr[i]-48;
temp.clear();
}
}
else (arr[i]>='a'&&arr[i]<='z')
temp.push_back(arr[i]);
}
map<string, int>::iterator itr;
if(temp.length())
m[temp]+=1;
temp.clear();
for(itr=m.begin();itr!=m.end();++itr)
{
temp.append(itr->first);
if(itr->second>1)
temp.push_back(itr->second+48);
}
return temp;
}