今天练习了一下堆栈的使用:
一、利用堆栈计算逆向波兰表达式:“3,4,*,1,2,+,+” 》》 3 * 4 + (1+2) = 15
将数字逐一压入到堆栈中,如果遇到运算符就pop出两个数组进行计算,并将结果压回到堆栈中;
首先判断一下边界条件:如果读入的字符是运算符但是堆栈中没有2个或以上的数组,说明不成立返回false;
然后根据读入是数字或操作符做相应的操作;
最后堆上的数字就是最后的结果;
import java.util.Stack;
public class ReversePolishExpr {
private String string;
Stack<Integer> stack = new Stack<Integer>();
public ReversePolishExpr(String string){
this.string = string;
}
public int isCalculator() throws Exception{
String[] tem = string.split(",");
for(int i=0;i<tem.length;i++){
if(isOperation(tem[i]) && stack.size()<2){
return -1;
}
if(isOperation(tem[i])){
twoNumCal(tem[i]);
}else{
stack.push(Integer.valueOf(tem[i]));
}
}
return stack.pop();
}
public boolean isOperation(String s){
if(s.equals("+") == true || s.equals("-") == true
|| s.equals("*") == true ||s.equals("/") == true){
return true;
}else{
return false;
}
}
public void twoNumCal(String s) throws Exception{
int op1 = stack.pop();
int op2 = stack.pop();
switch(s){
case "+":
stack.push(op1+op2);
break;
case "-":
stack.push(op1-op2);
break;
case "*":
stack.push(op1*op2);
break;
case "/":
stack.push(op1/op2);
break;
default:
throw new Exception("Illegal character!");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ReversePolishExpr rp = new ReversePolishExpr("3,4,*,1,2,+,+");
try {
System.out.println("The result of reverse polish express is " + rp.isCalculator());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
第二个是返回堆栈当前所有元素中值最大那个元素,时间复杂度为O(1):
例如stack: 5, 4, 2, 3, 6, 1, 10, 8 返回的就是10
因为是时间度为1,所以只能操作一次,那我们就需要考虑空间上能不能有所帮助:
我们同样申请一个新的堆栈,和一个值maxVal
将序列中的数依次压入到堆栈中,如果当前压入的值大于maxVal,更新maxVal并将maxVal压入到新建的堆栈maxStack中
注意点:在这当中如果有弹出元素,判断是否是当前最大值,如果是就把从stack和maxStack中弹出,把maxVal值设置成maxStack栈顶上的元素
空间复杂度为O(n)
package ch04_02;
import java.util.Stack;
public class MaxStack {
Stack<Integer> stack = new Stack<Integer>();
private int maxval = 0;
Stack<Integer> maxStack = new Stack<Integer>();
public void push(int var){
if(var > maxval){
maxval = var;
maxStack.push(maxval);
}
stack.push(var);
}
public int peek(){
return stack.peek();
}
public int pop(){
if(stack.peek() == maxval){
maxStack.pop();
maxval = maxStack.peek();
}
return stack.pop();
}
public int max(){
return maxStack.peek();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MaxStack ms = new MaxStack();
ms.push(5);
ms.push(4);
ms.push(2);
ms.push(3);
System.out.println("Max Val in stack is : " + ms.max());
ms.push(6);
ms.push(1);
ms.push(10);
ms.push(8);
System.out.println("Max Val in stack is : " + ms.max());
ms.pop();
ms.pop();
System.out.println("Max Val in stack is : " + ms.max());
ms.push(7);
System.out.println("Max Val in stack is : " + ms.max());
}
}
第三个:判断括号的匹配
这个题只要判断是“(”还是“ )”,如果是" ( "就把它压入到堆栈中,如果是“ ) ”就需要判断了,
首先如果读取当前的字符是" ) ",判断堆栈中是否值,如果有就pop(),如果堆栈为空则判断为不匹配。
遍历完之后如果发现堆栈不为空,说明还有“(”,判断为不匹配
package ch04_03;
import java.util.Stack;
public class stackStringMatch {
Stack<Character> stack = new Stack<Character>();
private String parents = "";
public stackStringMatch(String parents){
this.parents = parents;
}
public boolean isMatch() throws Exception{
int len = parents.length();
for(int i=0;i<len;i++){
if(parents.charAt(i) == '('){
stack.push(parents.charAt(i));
}else if(parents.charAt(i) == ')'){
if(stack.size() == 0 || stack.pop() != '(')//if(stack.size() == 0){
return false;
}else{
throw new Exception("Illegal character");
}
// }else{
// stack.pop();
// //return true;
// }
}
if(stack.size() != 0){
return false;
}
return true;
}
public static void main(String[] args){
String parents = "(())(()))";
stackStringMatch test = new stackStringMatch(parents);
try{
System.out.println(test.isMatch());
}catch(Exception e){
e.printStackTrace();
}
}
}