JAVA版本
思路:本题使用栈的方法来完成。本题相当于后缀表达式求值,也是与匹配相关,所以也是使用栈的思路。
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (int i =0;i<tokens.length;i++){
if(tokens[i].equals("+")){
stack.push((stack.pop() + stack.pop()));
}else if (tokens[i].equals("-")){
stack.push((-stack.pop() + stack.pop()));
}else if(tokens[i].equals("*")){
stack.push((stack.pop() * stack.pop()));
}else if(tokens[i].equals("/")){
int chushu = stack.pop();
int beichushu = stack.pop();
stack.push(beichushu / chushu);
}else{
stack.push(Integer.valueOf(tokens[i]));
}
}
return stack.pop();
}
}
注意:
1.注意先出栈的是作为符号后面的值,相当于除数,减数,第二次弹出的数作为被除数、被加数之类。
2.String类型转化为Int类型的方法。
Integer.valueOf();
Integer.parseInt();