题目链接:evaluate-reverse-polish-notation
import java.util.Stack; /** * 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 * */ public class EvaluateReversePolishNotation { // 20 / 20 test cases passed. // Status: Accepted // Runtime: 346 ms // Submitted: 0 minutes ago //时间复杂度O(n) 空间复杂度O(n) public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<Integer>(); for (String s : tokens) { if(isOp(s)) { stack.push(operation(stack.pop(), s, stack.pop())); } else { stack.push(stringToInt(s)); } } return stack.pop(); } //判断是否为操作符 public boolean isOp(String s) { if(s.equals("+") ||s.equals("-") ||s.equals("*") ||s.equals("/")) { return true; } else { return false; } } //对两个数进行运算符操作 public int operation(int b, String s, int a) { if(s.equals("+")) return a + b; else if(s.equals("-")) return a - b; else if(s.equals("*")) return a * b; else return a / b; } //将数字字符串转化成数字 public int stringToInt(String s) { int n = 0; int flag = 1; for (Character c : s.toCharArray()) { //判断是否为负数 if(c == '-') { flag = -1; continue; } n = 10 * n + c - '0'; } return flag * n; } public static void main(String[] args) { // TODO Auto-generated method stub } }
[LeetCode 150] Evaluate Reverse Polish Notation
原文地址:http://blog.csdn.net/ever223/article/details/44701279