您的位置:首页 > 其它

利用栈结构进行括号的匹配

2014-04-12 17:12 399 查看
package none003分隔符匹配;
//利用栈结构进行括号的匹配
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BracketApp {

/**
* @param args
*/
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub

Stack3 s3=new Stack3(60);
System.out.println("please input sentences you want to test the bracket:");
System.out.flush();
String sin=getInput();
int flag=0;
for(int i=0;i<sin.length();i++){
char k=sin.charAt(i);
if((k=='['||k=='{'||k=='(')&&flag==0){
s3.push(k);
flag=1;
}
if((k==')'||k=='}'||k==']')&&flag==0){
System.out.println("*******括号匹配不正确!!!**********");
System.out.print(i);
break;
}
if(flag==1&&(k=='['||k=='{'||k=='(')){
s3.push(k);
}
if(flag==1&&(k==')'||k=='}'||k==']')){
if(s3.peek()=='('&&k==')'){
s3.pop();
}else if(s3.peek()=='{'&&k=='}'){
s3.pop();
}else if(s3.peek()=='['&&k==']'){
s3.pop();
}else{
System.out.println("*******括号匹配不正确!!!**********");
System.out.print(i);
break;}
}
}

}
public static String getInput() throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
return br.readLine();
}

}
class Stack3{
int items;
char[] arrayStack;
int s;
Stack3(int  max){
s=max;
arrayStack=new char[s];
items=-1;
}
public void push(char value){
if(items==s-1) System.out.println("栈已经等于最大值了。");
else arrayStack[++items]=value;
}
public char pop(){
return arrayStack[items--];
}
public boolean isEmpty(){
return items==-1;
}
public char peek(){
if(items==-1) return 'F';
else return arrayStack[items];
}
public boolean isFull(){
return items==s-1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: