题解 | #逆波兰表达式求值#
逆波兰表达式求值
https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382
使用栈求解很方便得到:
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串一维数组 * @return int整型 */ public int evalRPN (String[] tokens) { // write code here int tmp=0; Stack<Integer> stack=new Stack<>(); int n = tokens.length; int x; for(int i=0;i<n;i++){ switch(tokens[i]){ case "+": tmp = stack.pop()+stack.pop(); stack.push(tmp); break; case "-": x=stack.pop(); tmp = stack.pop()-x; stack.push(tmp); break; case "*": tmp = stack.pop()*stack.pop(); stack.push(tmp); break; case "/": x=stack.pop(); tmp = stack.pop()/x; stack.push(tmp); break; default: stack.push(Integer.parseInt(tokens[i])); } } return stack.pop(); } }