分隔符匹配

/*
 * 本程序只要是用于括号匹配,使用栈的后进先出
 */
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();




}


}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值