forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate-reverse-polish-notation.cpp
More file actions
38 lines (36 loc) · 967 Bytes
/
evaluate-reverse-polish-notation.cpp
File metadata and controls
38 lines (36 loc) · 967 Bytes
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
// Time: O(n)
// Space: O(n)
class Solution {
public:
int evalRPN(vector<string>& tokens) {
if (tokens.empty()) {
return 0;
}
stack<string> s;
for (const auto& tok : tokens) {
if (!is_operator(tok)) {
s.emplace(tok);
} else {
auto&& y = stoi(s.top());
s.pop();
auto&& x = stoi(s.top());
s.pop();
if (tok[0] == '+') {
x += y;
} else if (tok[0] == '-') {
x -= y;
} else if (tok[0] == '*') {
x *= y;
} else {
x /= y;
}
s.emplace(to_string(x));
}
}
return stoi(s.top());
}
private:
bool is_operator(const string& op) {
return op.length() == 1 && string("+-*/").find(op) != string::npos;
}
};