LeetCode_002:Evaluate Reverse Polish Notation

来源:互联网 发布:linux expec参数怎么用 编辑:程序博客网 时间:2024/05/16 09:01
package com.abuge;import java.util.Stack;/** * 需求: * 给定一组逆波兰表达式,求其表达式的值 * 思路&步骤: * 1、利用出栈和入栈实现表达式 * 2、对运算符进行判断,将字符串转换成int型,进行运算 * 3、考虑极限情况(只有一个字符串)以及减法和除法的顺序 * @author AbuGe * */public class Solution {public static int evalRPN(String[] tokens){Stack<String> stack = new Stack<String>();int len = tokens.length;int result = 0;if(len == 1){result = Integer.parseInt(tokens[0]);}else{for(int i = 0 ; i < len; i++){switch(tokens[i]){case "+":int a = Integer.parseInt(stack.pop());int b = Integer.parseInt(stack.pop());result = a + b;String str = String.valueOf(result);stack.push(str);break;case "-":a = Integer.parseInt(stack.pop());b = Integer.parseInt(stack.pop());result = b - a;str = String.valueOf(result);stack.push(str);break;case "*":a = Integer.parseInt(stack.pop());b = Integer.parseInt(stack.pop());result = (a * b);str = String.valueOf(result);stack.push(str);break;case "/":a = Integer.parseInt(stack.pop());b = Integer.parseInt(stack.pop());result = (b / a);str = String.valueOf(result);stack.push(str);break;default:stack.push(tokens[i]);break;}}}return result;}public static void main(String[] args){String[] str = {"2", "1", "+", "3", "*"};String[] str2 = {"4", "13", "5", "/", "+"};int reslut1 = evalRPN(str);System.out.println(reslut1);System.out.println("---------------------------");int result2 = evalRPN(str2);System.out.println(result2);}}

0 0