您的位置:首页 > 编程语言 > Lua

LeetCode150 Evaluate Reverse Polish Notation java题解

2015-06-30 10:13 495 查看
题目:

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

解题:
这题是栈的一个经典应用,也比较简单,思路就是:遇到数字就进栈,遇到运算符号就出栈两个数字然后再将计算结果进栈。

代码:

import java.util.Stack;

public class LeetCode150_EvaluateReversePolishNotation {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] s={"4","-2","/","2","-3","-","-"};
System.out.println(evalRPN(s));

}

public static int evalRPN(String[] tokens) {
int length=tokens.length;
Stack<Integer> stack =new Stack<>();

for(int i=0;i<length;i++)
{
if(!isOperator(tokens[i]))
stack.push(Integer.parseInt(tokens[i]));
else {
int operaNum2=stack.pop();
int operaNum1=stack.pop();
if(tokens[i].equals("+"))
stack.push(operaNum1+operaNum2);
else if(tokens[i].equals("-"))
stack.push(operaNum1-operaNum2);
else if(tokens[i].equals("*"))
stack.push(operaNum1*operaNum2);
else {
stack.push(operaNum1/operaNum2);
}
}

}

return stack.pop();

}

public static boolean isOperator(String s)
{
if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/"))
return true;
else
return false;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: