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

leetcode--evaluate-reverse-polish-notation

2017-06-30 15:23 447 查看
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.*;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stackNum=new Stack<>();
int len=tokens.length;
for(int i=0;i<len;i++){
try{
stackNum.push(Integer.parseInt(tokens[i]));
}catch(Exception e){
String operation=tokens[i];
int numA=stackNum.pop();
int numB=stackNum.pop();
switch(operation){
case "+":
stackNum.push(numB+numA);
break;
case "-":
stackNum.push(numB-numA);
break;
case "*":
stackNum.push(numB*numA);
break;
case "/":
stackNum.push(numB/numA);
break;
}
}
}
return stackNum.pop();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: