给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入格式:
输入在一行中给出一行字符串,不超过100个字符,可能包括括号、数字、字母、标点符号、空格。
输出格式:
如果括号配对,输出yes,否则输出no。
输入样例1:
sin(10+20)
输出样例1:
yes
输入样例2:
{[}]
输出样例2:
no
程序代码:
import java.util.Scanner;
class Node{
Node next;
char data;
Node(){
}
Node(char data){
this.data = data;
}
}
class Stack{
Node top;
Node base;
Stack(){
top = null;
}
public void push(char data){
Node node = new Node(data);
node.next = top;
top = node;
}
public char getElem(){
if (top == null)
return ‘1’;
return top.data;
}
public boolean stackEmpty(){
if (top == null)
return true;
else
return false;
}
public void pop(){
if (top == null)
return;
top = top.next;
}
}
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String a = input.nextLine();
Stack stack = new Stack();
for (int i = 0; i < a.length(); i++){
switch(a.charAt(i)){
case ‘(‘:stack.push(‘(‘);break;
case ‘[‘:stack.push(‘[‘);break;
case ‘{‘:stack.push(‘{‘);break;
case ‘)’:
if (stack.getElem() != ‘(‘){
System.out.print(“no”);
System.exit(0);
}
stack.pop();
break;
case ‘]’:
if (stack.getElem() != ‘[‘){
System.out.print(“no”);
System.exit(0);
}
stack.pop();
break;
case ‘}’:
if (stack.getElem() != ‘{‘){
System.out.print(“no”);
System.exit(0);
}
stack.pop();
break;
}
}
if (stack.stackEmpty()){
System.out.print(“yes”);
}
else
System.out.print(“no”);
}
}