OK代表匹配成功
NO代表匹配失败
package Test;
import java.util.Iterator;public class stack<Item> implements Iterable<Item>{
private int N;
private Node First;
private class Node{
Item item;
Node next;
}
public boolean isEmpty(){
return First==null;
}
public int size(){
return N;
}
public void insert(Item item){
Node old=First;
First=new Node();
First.item=item;
First.next=old;
N++;
}
public Item del(){
if(!isEmpty()){
Item temp=First.item;
First=First.next;
N--;
return temp;
}
return null;
}
@Override
public Iterator<Item> iterator() {
// TODO Auto-generated method stub
return null;
}
private class LinkIterator implements Iterator<Item>{
private Node temp=First;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return temp!=null;
}
@Override
public Item next() {
// TODO Auto-generated method stub
Item item=temp.item;
temp=temp.next;
return item;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}}
public static void main(String args[]){
System.out.print(A("{(())[]}"));
}
private static int A(String temp) {
stack<String> stack=new stack<String>();
char[] ch=temp.toCharArray();
for(int i=0;i<ch.length;i++){
if(ch[i]=='{'){
stack.insert("{");
}
if(ch[i]=='('){
stack.insert("(");
}
if(ch[i]=='['){
stack.insert("[");
}
if(ch[i]==')'){
if(stack.del()!="("){
System.out.print("No");
return -1;
};
}
if(ch[i]=='}'){
if(stack.del()!="{"){
System.out.print("No");
return -1;
};
}
if(ch[i]==']'){
if(stack.del()!="["){
System.out.print("No");
return -1;
};
}
}
if(stack.isEmpty()) {
System.out.print("OK");
return 0;
}
else{System.out.print("No");
return -1;}
}
}