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

Leetcode-evaluate-reverse-polish-notation

2016-07-16 20:16 405 查看


题目描述

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<String> stack = new Stack<String>();

for(int i=0; i<tokens.length; i++){
if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")){
String two = stack.pop();
String one = stack.pop();
int a = Integer.parseInt(one);
int b = Integer.parseInt(two);
int res = 0;
if(tokens[i].equals("+")){
res = a + b;
}
if(tokens[i].equals("-")){
res = a - b;
}
if(tokens[i].equals("*")){
res = a * b;
}
if(tokens[i].equals("/")){
res = a / b;
}
stack.push(String.valueOf(res));
}else{
stack.push(tokens[i]);
}
}

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