-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path227.cpp
More file actions
55 lines (52 loc) · 1.51 KB
/
227.cpp
File metadata and controls
55 lines (52 loc) · 1.51 KB
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
class Solution {
public:
int calculate(int a, int b, char c){
if(c=='+')
return a+b;
if(c=='-')
return a-b;
if(c=='*')
return a*b;
return a/b;
}
int calculate(string s) {
unordered_map<char,int> precedence;
precedence['+'] = 0;precedence['-'] = 0;
precedence['/'] = 1;precedence['*'] = 1;
stack<int> digits;
digits.push(0);
stack<char> sign;
int n = s.size();
string nums = "";
for(int i=0; i<n; i++){
if(isdigit(s[i])){
nums += s[i];
continue;
}
if(nums.size()!=0){
digits.push(stoi(nums));
nums = "";
}
if(s[i]!=' '){
while(!sign.empty() && precedence[sign.top()]>=precedence[s[i]]){
int b = digits.top();digits.pop();
int a = digits.top();digits.pop();
int c = calculate(a,b,sign.top());
digits.push(c);
sign.pop();
}
sign.push(s[i]);
}
}
if(nums.size()!=0)
digits.push(stoi(nums));
while(!sign.empty()){
int b = digits.top();digits.pop();
int a = digits.top();digits.pop();
int c = calculate(a,b,sign.top());
digits.push(c);
sign.pop();
}
return digits.top();
}
};