# [Leetcode]_150 Evaluate Reverse Polish Notation

/**
*  Index: 150
*  Title: Evaluate Reverse Polish Notation
*  Author: ltree98
**/


# 题意

• 除法运算，需要向下取整
• 给定的表达式一定合法。即一定会有个最终值，不会有除0等不合法行为

# 我的

## 实现

class Solution {
public:
int evalRPN(vector<string>& tokens) {

for(int i = 0; i < tokens.size(); i++)  {
if(tokens[i][0] == '+') {
}
else if(tokens[i][0] == '-' && tokens[i].length() == 1) {
}
else if(tokens[i][0] == '*')    {
}
else if(tokens[i][0] == '/') {
}
else    {
int val = std::stoi(tokens[i]);
}
}

}
};


# 进阶

## 实现

class Solution {
public:
int evalRPN(vector<string>& tokens) {
unordered_map<string, function<int (int, int) > > map = {
{ "+" , [] (int a, int b) { return a + b; } },
{ "-" , [] (int a, int b) { return a - b; } },
{ "*" , [] (int a, int b) { return a * b; } },
{ "/" , [] (int a, int b) { return a / b; } }
};
std::stack<int> stack;
for (string& s : tokens) {
if (!map.count(s)) {
stack.push(stoi(s));
} else {
int op1 = stack.top();
stack.pop();
int op2 = stack.top();
stack.pop();
stack.push(map[s](op2, op1));
}
}
return stack.top();
}
};


author: hercule24

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客