lintcode-424-逆波兰表达式求值
424-逆波兰表达式求值
求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。样例
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6标签
领英 栈
思路
- 利用栈,首先遍历字符串数组,若遇到操作数,如 "1","23" 等,则将其转化为整数并入栈
- 若遇到操作符,如 "+","-","*","/",则将栈顶元素与次栈顶元素按操作符进行运算,并将运算结果入栈(栈顶元素与次栈顶元素要弹出栈)
- 最后,字符串数组遍历结束,栈内唯一的元素即运算结果
code
class Solution {
public:
/*
* @param tokens: The Reverse Polish Notation
* @return: the value
*/
int evalRPN(vector<string> tokens) {
// write your code here
int size = tokens.size();
if (size <= 0) {
return 0;
}
stack<int> stack;
for (int i = 0; i < size; i++) {
if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") {
stack.push(atoi(tokens[i].c_str()));
}
else {
int num1 = stack.top();
stack.pop();
int num2 = stack.top();
stack.pop();
int num3 = 0;
if (tokens[i] == "+") {
num3 = num2 + num1;
}
else if (tokens[i] == "-") {
num3 = num2 - num1;
}
else if (tokens[i] == "*") {
num3 = num2 * num1;
}
else if (tokens[i] == "/") {
num3 = num2 / num1;
}
stack.push(num3);
}
}
return stack.top();
}
};