题目描述
检查字符串中方括号、圆括号和花括号是否配对
输入
每个字符串一行,以0表示输入结束
输出
true 或者 false 每个一行
样例输入
(12,11,44,[6,[9]),(#)
([#],([2],3,1}
([#],([2],3,1),7)
0
样例输出
false
false
true
代码实现
import java.util.Scanner;
import java.util.Stack;
public class Bracket {
Stack<String> result=new Stack<String>();
Stack<String> result1=new Stack<String>();
public Bracket(){
Scanner sc=new Scanner(System.in);
String infix;
while(!"0".equals(infix = sc.nextLine())){
Stack<String> stack=new SeqStack<String>(infix.length());
for(int i=0;i<infix.length();i++){
char ch=infix.charAt(i);
switch(ch){
case'(':
stack.push(ch+"");
break;
case')':
if(!stack.isEmpty()&&stack.peek().equals("("))
stack.pop();
else
stack.push(ch+"");
break;
case'[':
stack.push(ch+"");
break;
case']':
if(!stack.isEmpty()&&stack.peek().equals("["))
stack.pop();
else
stack.push(ch+"");
break;
case'{':
stack.push(ch+"");
break;
case'}':
if(!stack.isEmpty()&&stack.peek().equals("{"))
stack.pop();
else
stack.push(ch+"");
break;
}
}
if(stack.isEmpty())
result.push("true");
else
result.push("false");
}
while(!result.isEmpty()){
result1.push(result.peek());
result.pop();
}
while(!result1.isEmpty()){
System.out.println(result1.peek());
result1.pop();
}
}
public static void main(String args[]){
Bracket b=new Bracket();
}
}
class SeqStack<T> extends Stack<String> {
public SeqStack(int length) {
// TODO Auto-generated constructor stub
}
}