Leetcode---逆波兰表达式求值--栈

逆波兰表达式求值

题目链接:添加链接描述

思路:

逆波兰式是典型的运用栈结构进行运算的
不仅仅此处使用栈结构求解,包括构造一个逆波兰式也是使用栈结构构成的,对于构造逆波兰式,此处不做多余的说明
整个流程很简单,遍历整个string数组,碰到的是数字就入栈,碰到的是字符,就出栈两个数作为操作数进行运算,这里需要注意两个数字的操作次序,比如0/3不要写成3/0
最终遍历完整个数组,栈当中也必然只含有一个最终结果值,直接输出即可
这里程序可以做进一步优化,就是栈中不存放字符串,这样操作较麻烦,首先就将字符串转为整数较方便。

	public int evalRPN(String[] tokens) {
		Stack<String> stack = new Stack<String>();
		for(int i=0;i<tokens.length;i++) {
			switch(tokens[i]) {
				case "+":{
					String op1 = stack.pop();
					String op2 = stack.pop();
					stack.push(new Integer(Integer.parseInt(op2)+Integer.parseInt(op1)).toString());
					break;
				}
				case "-":{
					String op1 = stack.pop();
					String op2 = stack.pop();
					stack.push(new Integer(Integer.parseInt(op2)-Integer.parseInt(op1)).toString());
					break;
				}
				case "*":{
					String op1 = stack.pop();
					String op2 = stack.pop();
					stack.push(new Integer(Integer.parseInt(op2)*Integer.parseInt(op1)).toString());
					break;
				}
				case "/":{
					String op1 = stack.pop();
					String op2 = stack.pop();
					stack.push(new Integer(Integer.parseInt(op2)/Integer.parseInt(op1)).toString());
					break;
				}
				default:{
					stack.push(tokens[i]);
				}
			}
		}
		return Integer.parseInt(stack.pop());
    }

猜你喜欢

转载自blog.csdn.net/tiaochewang219/article/details/85805032