利用反波兰法求值


[“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<Integer> stack = new Stack<Integer>();
        for(int i = 0; i < tokens.length; i++) {
            if(tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") {
                stack.push(Integer.parseInt(tokens[i]));
            }
            else {
                String sign = tokens[i];
                int b = stack.pop();
                int a = stack.pop();
                try{
                    switch (sign) {
                        case "+" :
                            stack.push(a + b);
                            break;
                        case "-" :
                            stack.push(a - b);
                            break;
                        case "*" :
                            stack.push(a * b);
                            break;
                        case "/" :
                            stack.push(a / b);
                            break;
                    }
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return stack.pop();
    }
}

猜你喜欢

转载自blog.csdn.net/w1375834506/article/details/88877921