-
Notifications
You must be signed in to change notification settings - Fork 0
/
Convert Expression to Reverse Polish Notation.cpp
42 lines (42 loc) · 1.28 KB
/
Convert Expression to Reverse Polish Notation.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
class Solution {
public:
/**
* @param expression: A string array
* @return: The Reverse Polish notation of this expression
*/
vector<string> convertToRPN(vector<string> &expression) {
// write your code here
stack<char> ops;
vector<string> ans;
int a[128];
a['*'] = a['/'] = 2;
a['+'] = a['-'] = 1;
a['('] = 0;
for(auto& s:expression) {
if(isdigit(s[0])) ans.push_back(s);
else {
switch(s[0]) {
case ')':
while(ops.top() != '(') {
ans.push_back(string(1, ops.top()));
ops.pop();
}
ops.pop(); break;
case '(':
ops.push('('); break;
default:
while(!ops.empty() && a[ops.top()] >= a[s[0]]) {
ans.push_back(string(1, ops.top()));
ops.pop();
}
ops.push(s[0]);
}
}
}
while(!ops.empty()) {
ans.push_back(string(1, ops.top()));
ops.pop();
}
return ans;
}
};