栈解决括号匹配

package coding;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;

class Stack{
    char[] data;
    int maxSize;
    int top;
Scanner input=new Scanner(System.in);
public Stack(int maxSize){
    this.maxSize=maxSize;
    data=new char[maxSize];
    top=-1;
}
public int getSize(){
    return maxSize;
}
public int getElementCount(){
    return top;
}

public boolean isEmpty(){
    return top==-1;
}

public boolean isFull(){
    return top+1==maxSize;
}

public boolean push(char data){
    if(isFull()){
        System.out.println("栈已经满");
        return false;
    }
    this.data[++top]=data;
    return true;
}
public char pop(){
    if(isEmpty()){
        try {
            throw new Exception("栈已空");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return this.data[top--];

}
public char peek(){
    return this.data[getElementCount()];
}
void pipei()throws Exception{
    Stack stack;
    char ch,temp;
    int match;
    stack=new Stack(0);
 BufferedReader Reader=new BufferedReader(new InputStreamReader(System.in));
 ch=(char)Reader.read();
 while(ch!='0'){
     if(getElementCount()==-1){
         push(ch);
     }else{
         temp=pop();
         match=0;
     if(temp=='('&&ch==')'){
         match=1;
     }
     if(temp=='['&&ch==']'){
        match=1; 
     }
     if(temp=='<'&&ch=='>'){
         match=1;
     }
     if(temp=='{'&&ch=='}'){
         match=1;
     }
     if(match==0){
         push(temp);
         push(ch);
     }
     }
     ch=(char)Reader.read();
 }
 if(getElementCount()==-1){
     System.out.println("括号完全匹配");
 }
 else{
     System.out.println("输入的括号bu匹配,请检查!\n");
 }
}
}


public class cha07_blanket {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
     String go;
     Scanner input=new Scanner (System.in);
     Stack s=new Stack(20);
     System.out.println("括号匹配问题");
     do{
         System.out.println("请输入一组括号组合,以0表示结束");
         s.pipei();
         System.out.println("继续玩吗?(y/n)");
         go=input.next();
     }while(go.equalsIgnoreCase("y"));
    System.out.println("游戏结束!");
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值