您的位置:首页 > 其它

分隔符匹配

2016-02-10 20:31 225 查看
/*

* 本程序只要是用于括号匹配,使用栈的后进先出

*/

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();

}

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