题目
根据逆波兰表示法,求表达式的值。
示例1:
输入: [“10”, “6”, “9”, “3”, “+”, “-11”, “", “/”, "”, “17”, “+”, “5”
“+”]
输出: 22
解释: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
示例2
输入: [“2”, “1”, “+”, “3”, “*”]
输出: 9
解释: ((2 + 1) * 3) = 9
示例3
输入: [“4”, “13”, “5”, “/”, “+”]
输出: 6
解释: (4 + (13 / 5)) = 6
算法
1、数字:进栈
2、符号:将数字出栈进行计算,并将计算结果重新压入栈
最后栈中只剩一个元素,就是结果
注意:由此我先想到的如何判断一个字符串是数字还是符号,有两种方法:
1、正则表达式判断
2、用try…catch语句,如下
try { //如果是数字的话,进栈
int num=Integer.valueOf(s1); //如果能转换成int型就是数字
s.push(num);
}catch(Exception e){//如果是符号的话,捕获异常
//中间的代码块为各种运算符号对应的情况
}
这种方法显然非常多余,因为只需将四种“+”,“-”,“*”,“/”的情况摘出来以后,剩下的情况一定就是数字了,完全不需要判断这一步骤
代码
1、不用是判断否是数字的代码(用栈结构实现)
运行时间12ms
相比用try…catch语句进行判断的情况,运行时间缩短一半,因为try…catch语句每次循环都要进行int转换的判断,而switch不需要进型int型的转换,直接匹配
public int evalRPN(String[] tokens) {
Stack<Integer> s=new Stack<>();
int size=tokens.length;
int y=0;//每一步的结果
for(int i=0;i<size;i++) {
String s1=tokens[i];
int x=0;
switch(s1) {
case "+":
x=s.pop();
y=x+s.pop();
break;
case "-":
x=s.pop();
y=s.pop()-x;
break;
case "*":
x=s.pop();
y=x*s.pop();
break;
case "/":
x=s.pop();
y=s.pop()/x;
break;
default:
y=Integer.valueOf(s1);
break;
}
s.push(y);
}
return y;
}
2、用数组实现
运行时间3ms
public int evalRPN(String[] tokens) {
int size=tokens.length;
int top=-1;
int[] s=new int[size];
for(int i=0;i<size;i++) {
String s1=tokens[i];
switch(s1) {
case "+":
s[top-1]+=s[top];//注意:s[top--]+=s[top]不可以
top--;
break;
case "-":
s[top-1]-=s[top];
top--;
break;
case "*":
s[top-1]*=s[top];
top--;
break;
case "/":
s[top-1]/=s[top];
top--;
break;
default:
s[++top]=Integer.valueOf(s1);
break;
}
}
return s[top];
}
注意:s[top-1]+=s[top]的计算结果不等于s[top–]+=s[top];
假设此时s[0]=3,s[1]=11,top=1,则
s[top–]+=s[top]的计算结果为:s[0]=3,s[1]=14,top=0;
s[top-1]+=s[top]的计算结果为:s[0]=14,s[1]=11,top=1;