import java.util.Deque;
import java.util.LinkedList;
import static jdk.nashorn.internal.runtime.JSType.isNumber;
//逆波兰表达式
public class Solution1 {
public int evalRPN(String[] tokens){
//用栈,遇到符号出两个,算完进栈
Deque<Integer> stack = new LinkedList<Integer>();
int n =tokens.length;
for(int i = 0;i < n;i++){
String token = tokens[i];
if(isNumber(token)){//判断token是否为数字,是则返回true
stack.push(Integer.parseInt(token));
//Integer.parseInt将整形数据Integer转换为基本数据类型int
}else{
int num1 = stack.pop();
int num2 = stack.pop();
switch(token){
case "+":
stack.push(num2 + num1);
break;
case "-":
stack.push(num2 - num1);
break;
case "*":
stack.push(num2 * num1);
break;
case "/":
stack.push(num2 / num1);
break;
default:
}
}
}
return stack.pop();
}
}
方法二:
public class Solution2 {
public int evalRPN(String [] tokens){
if(tokens.length == 0){
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
int n = tokens.length;
for (int i = 0; i < n; i++) {
if(("+".equals(tokens[i])) ||
("-".equals(tokens[i])) ||
("*".equals(tokens[i])) ||
("/".equals(tokens[i])) ){
int num1 = stack.pop();
int num2 = stack.pop();
if("+".equals(tokens[i])){
stack.push(num2 + num1);
}
if(("-".equals(tokens[i]))){
stack.push(num2 - num1);
}
if(("*".equals(tokens[i]))){
stack.push(num2 * num1);
}
if(("/".equals(tokens[i]))){
stack.push(num2 / num1);
}
}else{//数字
//用Integer类型数据表示一个数字
stack.push(Integer.valueOf(tokens[i]));
}
}
return stack.pop();
}
}