分隔符匹配

/*
 * 本程序只要是用於括號匹配,使用棧的後進先出
 */
package Demo2_Stack;
class Stacktn
{
private int maxsize;
private char [] arraystack;
private int top;
public Stacktn(int s)
{
this.maxsize = s;
this.arraystack = new char [maxsize];
this.top = -1;//初始時top指針是-1


}
//插入隊列操作
public void push(char i)


{  if(!isFull())
{
arraystack[++top] = i;
}




}
//取出棧元素操作
public char pop()
{
return arraystack[top--];
}
//查找棧元素操作
public char peek()
{
return arraystack[top];
}
//查看棧元素是否爲空
public boolean isEmpty()
{
return (top==-1);
}
//判斷棧元素是否已經滿了
public boolean isFull()
{
return top==(maxsize-1);
}




}






class Brake
{
private String input;
public Brake(String str)
{
input = str;

}
public void check()
{
int stackSize   = input.length();
Stacktn stackt = new Stacktn(stackSize);
for(int i= 0;i <input.length();i++)
{
char ch = input.charAt(i);
switch(ch)
{
case '{':
case '(':
case '[':
stackt.push(ch);//左括號入棧
System.out.print(ch);
break;
case ']':
case '}':
case ')':
//右括號,則將棧中元素出棧,然後比較
if(!stackt.isEmpty())
{
char chx = stackt.pop();
System.out.print(chx);
if((ch=='}'&&chx!='{')||(ch==']'&&chx!='[')||(ch==')'&&chx!='('))
{
System.out.println("error"+ch+"at"+i);
}
}
else {
System.out.println("error"+ch+"at"+i);
}
break;
default:
break;



}
}
if(!stackt.isEmpty())
{
System.out.println("Error:missing right delmiter");
}
}




}


public class stack_Demo {


public static void main(String[] args) {
Brake brake = new Brake("[(ssss)]sssss(");
brake.check();




}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章