1. 程式人生 > >棧解決括號匹配

棧解決括號匹配

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("遊戲結束!"); } }