[LeetCode 150]Evaluate Reverse Polish Notation

题目链接: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;elsereturn 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

相关文章:

你感兴趣的文章:

标签云: