判断输入的一串字符{}()【】是否按照正确格式书写

import java.util.Stack;

public class StackTest

{

 public static void main(String[] args) throws Exception{

  String s="{{(([[]]))}}";

  try{   Stack stk=new Stack();

    for(int i=0;i<s.length();i++){

   char c=s.charAt(i);

   if(c=='{') stk.push(new Character('}'));

   if(c=='[') stk.push(new Character(']'));

   if(c=='(') stk.push(new Character(')'));

   if(c=='}'||c==']'||c==')'){

    char c2=((Character) stk.pop()).charValue();

    if(c2!=c) throw new Exception("不匹配");

   }

    }

  if(!(stk.isEmpty())) throw new Exception("不匹配");

  System.out.println("匹配");

  }catch(Exception e){

   System.out.println("不匹配");

  }

 }

}

posted on 2013-10-15 09:20  知识海洋  阅读(337)  评论(0)    收藏  举报