题目:计算逆波兰表达式
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
题意:
计算一个逆波兰表示法的算术表达式。
有效的操作符有加减乘除,每一个操作数可能是一个整数或者另外的表达式。
思路:
逆波兰表达式就是把操作数放在前面,把操作符后置的一种写法。观察以上给出的例子可以看出第一个出现的运算符前面一定有两个数字,即操作数。运算过程中,遇到操作符,则取出前面的两个操作数进行运算,将运算结果存储到原来的位置,为下一次运算提供操作数。利用栈实现,先将给定表达式中的两个操作数压入栈中,每次遇到操作符就取出栈中的操作数做运算,将运算结果保存到栈中。运算之后,如果栈为空或者栈size大于1,说明出现错误。
代码:C++版:20ms
class Solution { public: int evalRPN(vector<string>& tokens) { if (tokens.size() == 1) return atoi(tokens[0].c_str()); stack<int> stk; for (int i=0; i<tokens.size(); ++i) { if (tokens[i]!="+" && tokens[i]!="-" && tokens[i]!="*" && tokens[i]!="/") { //如果不是操作符,直接入栈 stk.push(atoi(tokens[i].c_str())); } else { int operand1 = stk.top(); //取出两个操作数 stk.pop(); int operand2 = stk.top(); stk.pop(); if (tokens[i] == "+") stk.push(operand2 + operand1); //将运算结果入栈 else if (tokens[i] == "-") stk.push(operand2 - operand1); else if (tokens[i] == "*") stk.push(operand2 * operand1); else if (tokens[i] == "/") stk.push(operand2 / operand1); } } if (stk.size() == 1) { //只有栈的size为1时是正确的 return stk.top(); } else { return -1; } } };
代码:java版:15ms
public class Solution { public int evalRPN(String[] tokens) { int a, b; Stack<Integer> stack = new Stack<Integer>(); for (String s : tokens) { if (s.equals("+")) { a = stack.pop(); b = stack.pop(); stack.push(b + a); } else if (s.equals("-")) { a = stack.pop(); b = stack.pop(); stack.push(b - a); } else if (s.equals("*")) { a = stack.pop(); b = stack.pop(); stack.push(b * a); } else if (s.equals("/")) { a = stack.pop(); b = stack.pop(); stack.push(b / a); } else { stack.push(Integer.parseInt(s)); //操作数入栈 } } return stack.pop(); } }