LeetCode 150. 逆波兰表达式求值-java关键解释
原题链接
中等
作者:
OneDay1
,
2021-03-20 21:13:43
,
所有人可见
,
阅读 284
package leetcode练习题.每日一题;
import java.util.Set;
import java.util.Stack;
public class 逆波兰表达式求值 {
//声明一个栈保存整型,声明一个Set集合保存算数运算符
static Stack<Integer> stk = new Stack<Integer>();
static Set<String> s = Set.of("+","-","*","/");
public static void eval(String s){
int b = stk.peek();stk.pop();
int a = stk.peek();stk.pop();
if(s.equals("+")) stk.push(a+b);
else if(s.equals("-")) stk.push(a-b);
else if(s.equals("*")) stk.push(a*b);
else{
stk.push(a/b);
}
}
public static int evalRPN(String[] tokens) {
for (String t: tokens) {
//如果是数字,转换为整型保存到栈中---isDigit(char ch)
//因为数据中有两位数以及负数,且非数字的长度都是1
//所以需要特判一下
if(Character.isDigit(t.charAt(0)) || t.length() >1) stk.push(Integer.parseInt(t));
//不是整型则进行运算
else eval(t);
}
return stk.peek();
}
public static void main(String[] args) {
String[] tokens = {"10","6","9","3","+","-11","*","/","*","17","+","5","+"};
System.out.println(evalRPN(tokens));
}
}