您的位置:首页 > 其它

栈的应用(一)-括号匹配

2015-05-07 10:46 295 查看
package chapter4;

import java.util.Scanner;

public class Bracket {

 /**

  * @括号匹配a{b[c(d)e]f}

  */

 public static void main(String[] args) {

  String input;

  while(true){

   Scanner sc = new Scanner(System.in);

   input = sc.nextLine();

   if(input.equals(""))

    break;

   BraketChecker theChecker = new BraketChecker(input);

   theChecker.check();

  }

 }

}

class StackII{

 private int maxSize;

 private char[] stackArray;

 private int top;

 

 public StackII(int maxSize){

  this.maxSize = maxSize;

  stackArray = new char[this.maxSize];

  top = -1;

 }

 public void push(char value){

  stackArray[++top] = value;

 }

 public char pop(){

  return stackArray[top--];

 }

 public char peek(){

  return stackArray[top];

 }

 public boolean isEmpty(){

  return (top==-1);

 }

}

class BraketChecker{

  private String input;

  public BraketChecker(String in){

   input = in;

  }

  public void check(){

   int maxSize = input.length();

   StackII theStack = new StackII(maxSize);

   for(int i=0;i<maxSize;i++){

    char ch = input.charAt(i);

    switch(ch){

    case '{':

    case '(':

    case '[':

     theStack.push(ch); break;

    case '}':

    case ')':

    case ']':

     if(!theStack.isEmpty()){

      char temp = theStack.pop();

      if( (ch=='{' && temp!='}') || (ch=='(' && temp!=')') || (ch=='[' && temp!=']')  )

       System.out.println("error:"+ch+"at"+i);

     }

     else

      System.out.println("error:"+ch+"at"+i); break;

    default:break;

    }

   }

   if(!theStack.isEmpty())

    System.out.println("error:missing right delimiter");

  

  }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: