Difficulty: Medium
Classic problems after classic problems. If you know how the reverse polish notation, it is intuitive to use a stack to store all the numbers.
As we go through the symbols, if it is a number, we simply append it to the stack. If it is a operation, we pop two numbers from the stack, do the operation with the two numbers and append the result to the stack.
At the end, we can return the resulting number in the stack.
cppIS A STUPID AS LANGUAGE, BECAUSE WHAT DO YOU MEANVECTOR.POP_BACK()DOESN’T RETURN ME THE VALUE, IT JUST RETURNS VOID WHO MADE THIS SHI
class Solution {
public:
int evalRPN(vector<string>& tokens) {
vector<int> stack {};
unordered_set<string> symbol {"+", "-", "*", "/"};
for (string token: tokens) {
if (!symbol.contains(token)) {
stack.push_back(stoi(token));
} else {
int b = stack.back();
stack.pop_back();
int a = stack.back();
stack.pop_back();
if (token == "+") stack.push_back(a + b);
if (token == "-") stack.push_back(a - b);
if (token == "*") stack.push_back(a * b);
if (token == "/") stack.push_back(a / b);
}
}
return stack.back();
}
};
Time Complexity:
O(n)Space Complexity:
O(1)Time Taken:
15m 39s