题意:逆波兰表达式求值
思路:利用一个栈,遇到数字就进栈,遇到操作符就从栈里弹出两个数字进行计算,并将计算结果压入栈中。
代码:
public int CalNotation(String[] str) {
if(str == null || str.length == 0) return -1;
Stack<Integer>stack = new Stack<>();
int temp = 0;
for(int i = 0 ; i < str.length ; i++){
if(str[i].equals("+") || str[i].equals("-") || str[i].equals("*") || str[i].equals("/") ){
int a = stack.pop();
int b = stack.pop();
if(str[i].equals("+")){
temp = a + b;
}
if(str[i].equals("-")){
temp = a - b;
}
if(str[i].equals("*")){
temp = a * b;
}
if(str[i].equals("/")){
temp = a / b;
}
stack.push(temp);
}else{
stack.push(Integer.parseInt(str[i]));
}
}
return temp;
}
本文介绍了一种使用栈来解析并计算逆波兰表达式的算法。该算法通过遍历输入字符串,当遇到数字时将其压入栈中,而遇到运算符时则从栈中弹出两个数字进行计算并将结果重新压入栈中。最终栈顶元素即为表达式的计算结果。
309

被折叠的 条评论
为什么被折叠?



