首页 > 代码库 > 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);}}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。