1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00

cpp: add «150. Evaluate Reverse Polish Notation»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-01-30 10:31:30 +01:00
parent 3987abfd64
commit b71f3d7640
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,57 @@
#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;
}