1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/cpp/evaluate-reverse-polish-notation.cpp
Matej Focko 1eab058c56
style(cpp): reformat
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-05-17 18:23:03 +02:00

57 lines
1.6 KiB
C++

#include <cassert>
#include <functional>
#include <string>
#include <vector>
class Solution {
static auto
get_function(const std::string &op) -> std::function<int(int, int)> {
if (op == "+") {
return std::plus<int>{};
} else if (op == "-") {
return std::minus<int>{};
} else if (op == "*") {
return std::multiplies<int>{};
} else if (op == "/") {
return std::divides<int>{};
}
assert(false);
}
public:
auto evalRPN(const std::vector<std::string> &tokens) -> int {
std::vector<int> stack;
for (const auto &token : tokens) {
if (token == "+" || token == "-" || token == "*" || token == "/") {
assert(stack.size() >= 2);
int right = stack.back();
stack.pop_back();
int left = stack.back();
stack.pop_back();
stack.push_back(get_function(token)(left, right));
} else {
stack.push_back(std::stoi(token));
}
}
return stack.back();
}
};
int main() {
Solution s;
assert(s.evalRPN(std::vector<std::string>{
{"2"}, {"1"}, {"+"}, {"3"}, {"*"}}) == 9);
assert(s.evalRPN(std::vector<std::string>{
{"4"}, {"13"}, {"5"}, {"/"}, {"+"}}) == 6);
assert(s.evalRPN(std::vector<std::string>{{"10", "6", "9", "3", "+", "-11",
"*", "/", "*", "17", "+", "5",
"+"}}) == 22);
return 0;
}