forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert-expression-to-polish-notation.cpp
59 lines (56 loc) · 1.61 KB
/
convert-expression-to-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
58
59
// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param expression: A string array
* @return: The Polish notation of this expression
*/
vector<string> convertToPN(vector<string> &expression) {
vector<string> output;
infixToPrefix(expression, output);
return output;
}
// Convert Infix to Prefix Expression.
void infixToPrefix(vector<string>& infix, vector<string>& prefix) {
reverse(infix.begin(), infix.end());
stack<string> s;
for (auto& tok : infix) {
if (atoi(tok.c_str())) {
prefix.emplace_back(tok);
} else if (tok == ")") {
s.emplace(tok);
} else if (tok == "(") {
while (!s.empty()) {
tok = s.top();
s.pop();
if (tok == ")") {
break;
}
prefix.emplace_back(tok);
}
} else {
while (!s.empty() && precedence(tok) < precedence(s.top())) {
prefix.emplace_back(s.top());
s.pop();
}
s.emplace(tok);
}
}
while (!s.empty()) {
prefix.emplace_back(s.top());
s.pop();
}
reverse(prefix.begin(), prefix.end());
}
int precedence(string x) {
if (x == ")") {
return 0;
} else if (x == "+" || x == "-") {
return 1;
} else if (x == "*" || x == "/") {
return 2;
}
return 3;
}
};