算法思路:
题目的意思就是求后缀表达式的值,题目保证该后缀表达式是合法的,先设置一个int类型的栈。遍历该表达式,若是数字的字符串,将其转化为int类型后压入栈中,其中有个小问题,处理负数字符串要注意,其判定条件(个人想法)是:str[0]='-' && str.length>1
;否则,就是操作符,依次弹出2个数据,执行相应操作后压入栈中。遍历结束后,栈中只有一个元素,即返回结果。
该算法时间复杂度O(n),空间复杂度O(n)。参考代码:
//leetcode 20. Valid Parentheses
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for(int i=0;i<tokens.length;i++){
if(tokens[i].charAt(0)>='0'&&tokens[i].charAt(0)<='9'||
tokens[i].charAt(0)=='-'&&tokens[i].length()>1){
int num=0;
int j=0;
if(tokens[i].charAt(0)=='-')
j=1;
for(;j<tokens[i].length();j++){
num = num*10+tokens[i].charAt(j)-'0';
}
if(tokens[i].charAt(0)=='-')
num = num*(-1);
stack.push(num);
}else{
int y = stack.pop();
int x = stack.pop();
char op = tokens[i].charAt(0);
switch(op){
case '+':stack.push(x+y);break;
case '-':stack.push(x-y);break;
case '*':stack.push(x*y);break;
case '/':stack.push(x/y);break;
default:break;
}
}
}
return stack.pop();
}