首页 > 代码库 > leetcode-计算逆波兰表示法的值

leetcode-计算逆波兰表示法的值

package edu.bupt.cici.leetcode;import java.util.ArrayList;public class EvaluateReversePolishNotation {public int evalRPN(String[] tokens) {int temp = 0;int length = tokens.length;ArrayList<Integer> stack = new ArrayList<Integer>();for (int i = 0; i < length; i++) {if (!tokens[i].matches("^[\\+\\-*/]$")) {temp = Integer.parseInt(tokens[i]);stack.add(Integer.parseInt(tokens[i]));} else {switch (tokens[i]) {case "+":temp = stack.get(stack.size() - 2)+ stack.get(stack.size() - 1);break;case "-":temp = stack.get(stack.size() - 2)- stack.get(stack.size() - 1);break;case "*":temp = stack.get(stack.size() - 2)* stack.get(stack.size() - 1);break;case "/":temp = stack.get(stack.size() - 2)/ stack.get(stack.size() - 1);break;default:break;}stack.remove(stack.size() - 1);stack.remove(stack.size() - 1);stack.add(temp);}}return temp;}public static void main(String[] args) {// TODO Auto-generated method stubString[] ipt = { "-3","9","*" };EvaluateReversePolishNotation eRPN = new EvaluateReversePolishNotation();int opt = eRPN.evalRPN(ipt);System.out.println(opt);}}