-
Notifications
You must be signed in to change notification settings - Fork 3
/
726.cpp
80 lines (65 loc) · 1.9 KB
/
726.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
67
68
69
70
71
72
73
74
75
76
77
78
79
class Solution {
public:
bool isUpper(char c){
return 'A' <= c && c <= 'Z';
}
bool isLower(char c){
return 'a' <= c && c <= 'z';
}
bool isDigit(char c){
return '0' <= c && c <= '9';
}
bool isLetter(char c){
return isUpper(c) || isLower(c);
}
int char2digit(char c){
return c - '0';
}
int string2num(string s){
if (s == "") return 1;
return stoi(s);
}
unordered_map<string, int> chemicals;
void parse(string& formula, int& pos, int factor){
string number = "";
string chemical = "";
while (pos >= 0){
char c = formula[pos];
pos--;
if (isDigit(c)){
number = c + number;
}
else if (isLetter(c)){
chemical = c + chemical;
if (isUpper(c)){
chemicals[chemical] += string2num(number) * factor;
number = "";
chemical = "";
}
}
else if (c == ')'){
parse(formula, pos, factor * string2num(number));
number = "";
}
else if (c == '('){
break;
}
}
}
string countOfAtoms(string formula) {
int size = formula.size() - 1;
parse(formula, size, 1);
vector<string> chemical_names;
// sort by chemical
for (auto ch : chemicals) {
chemical_names.push_back(ch.first);
}
sort(chemical_names.begin(), chemical_names.end());
string out;
for (string chemical_name : chemical_names){
out += chemical_name;
out += (chemicals[chemical_name] > 1) ? to_string(chemicals[chemical_name]) : "";
}
return out;
}
};