# LeetCode 150 逆波兰表达式求值

class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for(String s : tokens){
int num1,num2;
//正则表达式匹配数字
if(s.matches("\\d+")){
int num = Integer.parseInt(s);
stack.push(num);
}else if(s.length()>1 && s.charAt(0)=='-'){//匹配负数
int num = Integer.parseInt(s);
stack.push(num);
}else{
switch(s){
case "+":
num1 = stack.pop();
num2 = stack.pop();
stack.push(num1+num2);
break;
case "-":
num1 = stack.pop();
num2 = stack.pop();
stack.push(num2-num1);
break;
case "*":
num1 = stack.pop();
num2 = stack.pop();
stack.push(num1*num2);
break;
case "/":
num1 = stack.pop();
num2 = stack.pop();
stack.push(num2/num1);
break;
}
}
}
return stack.pop();
}
}

|
10天前
|

golang力扣leetcode 399.除法求值
golang力扣leetcode 399.除法求值
29 0
|
10天前
leetcode代码记录（逆波兰表达式求值
leetcode代码记录（逆波兰表达式求值
14 0
|
10天前
|

leetcode 399 除法求值
leetcode 399 除法求值
14 1
|
10天前
|
Java
LeetCode题解-逆波兰表达式求值-Java

17 0
|
10天前
|
Go
golang力扣leetcode 150.逆波兰表达式求值
golang力扣leetcode 150.逆波兰表达式求值
23 0
|
10天前
|

☆打卡算法☆LeetCode 150. 逆波兰表达式求值 算法解析
☆打卡算法☆LeetCode 150. 逆波兰表达式求值 算法解析
38 0
|
6月前
|

41 0
|
1天前
|

6 1
|
1天前
|

JAVA数据结构刷题 -- 力扣二叉树
JAVA数据结构刷题 -- 力扣二叉树
7 0