package coding;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
class Stack{
char[] data;
int maxSize;
int top;
Scanner input=new Scanner(System.in);
public Stack(int maxSize){
this.maxSize=maxSize;
data=new char[maxSize];
top=-1;
}
public int getSize(){
return maxSize;
}
public int getElementCount(){
return top;
}
public boolean isEmpty(){
return top==-1;
}
public boolean isFull(){
return top+1==maxSize;
}
public boolean push(char data){
if(isFull()){
System.out.println("栈已经满");
return false;
}
this.data[++top]=data;
return true;
}
public char pop(){
if(isEmpty()){
try {
throw new Exception("栈已空");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return this.data[top--];
}
public char peek(){
return this.data[getElementCount()];
}
void pipei()throws Exception{
Stack stack;
char ch,temp;
int match;
stack=new Stack(0);
BufferedReader Reader=new BufferedReader(new InputStreamReader(System.in));
ch=(char)Reader.read();
while(ch!='0'){
if(getElementCount()==-1){
push(ch);
}else{
temp=pop();
match=0;
if(temp=='('&&ch==')'){
match=1;
}
if(temp=='['&&ch==']'){
match=1;
}
if(temp=='<'&&ch=='>'){
match=1;
}
if(temp=='{'&&ch=='}'){
match=1;
}
if(match==0){
push(temp);
push(ch);
}
}
ch=(char)Reader.read();
}
if(getElementCount()==-1){
System.out.println("括号完全匹配");
}
else{
System.out.println("输入的括号bu匹配,请检查!\n");
}
}
}
public class cha07_blanket {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String go;
Scanner input=new Scanner (System.in);
Stack s=new Stack(20);
System.out.println("括号匹配问题");
do{
System.out.println("请输入一组括号组合,以0表示结束");
s.pipei();
System.out.println("继续玩吗?(y/n)");
go=input.next();
}while(go.equalsIgnoreCase("y"));
System.out.println("游戏结束!");
}
}
栈解决括号匹配
最新推荐文章于 2022-05-11 22:48:32 发布