-
Notifications
You must be signed in to change notification settings - Fork 257
/
convert-expression-to-reverse-polish-notation.cpp
57 lines (54 loc) · 1.54 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param expression: A string array
* @return: The Reverse Polish notation of this expression
*/
vector<string> convertToRPN(vector<string> &expression) {
vector<string> output;
infixToPostfix(expression, output);
return output;
}
// Convert Infix to Postfix Expression.
void infixToPostfix(const vector<string>& infix, vector<string>& postfix) {
stack<string> s;
for (auto tok : infix) {
if (atoi(tok.c_str())) {
postfix.emplace_back(tok);
} else if (tok == "(") {
s.emplace(tok);
} else if (tok == ")") {
while (!s.empty()) {
tok = s.top();
s.pop();
if (tok == "(") {
break;
}
postfix.emplace_back(tok);
}
} else {
while (!s.empty() && precedence(tok) <= precedence(s.top())) {
postfix.emplace_back(s.top());
s.pop();
}
s.emplace(tok);
}
}
while (!s.empty()) {
postfix.emplace_back(s.top());
s.pop();
}
}
int precedence(string x) {
if (x == "(") {
return 0;
} else if (x == "+" || x == "-") {
return 1;
} else if (x == "*" || x == "/") {
return 2;
}
return 3;
}
};