package com.lulu.leetcode;
import java.util.Stack;
/**
* 波兰表达式求值(前缀表达式)---与后缀表达式不同的是计算两个数的值时,用第一个栈顶元素操作第二个栈顶元素
* 思路:
* 遇到变量或数字直接入栈;
* 遇到操作符计算栈顶两个元素的值,结果入栈
* @author lulu
*
*/
public class C_evalPN{
public int evalRPN(String[] tokens) {
if (tokens == null)
return 0;
Stack<String> stack = new Stack<String>();
int result = 0;
for (int i = 0; i < tokens.length; i++) {
String ch = tokens[i];
int num1 = 0;
int num2 = 0;
switch (ch) {
case "+":
num2 = Integer.parseInt(stack.pop());
num1 = Integer.parseInt(stack.pop());
result =num2+num1;
stack.push(result+"");
break;
case "-":
num2 = Integer.parseInt(stack.pop());
num1 = Integer.parseInt(stack.pop());
result =num2-num1;
stack.push(result+"");
break;
case "*":
num2 = Integer.parseInt(stack.pop());
num1 = Integer.parseInt(stack.pop());
result = num2 * num1;
stack.push(result+"");
break;
case "/":
num2 = Integer.parseInt(stack.pop());
num1 = Integer.parseInt(stack.pop());
result = num2 / num1;
stack.push(result+"");
break;
default:
stack.push(ch);
break;
}
}
if(!stack.isEmpty()){
return Integer.parseInt(stack.pop());
}
return result;
}
}
重拾编程之路--数据结构--前缀表示法求值
最新推荐文章于 2021-12-12 20:20:29 发布