public class Matcher {
public MatchRtnCode matcher(String str){
Stack<Character> s=new LLStack<Character>();
for(int i =0; i<str.length(); i++){
char c=str.charAt(i);
if(c=='{' || c=='[' || c=='('){
s.push(c);
}else if (c=='}'){
Character temp=s.pop();
if(temp!='{'){
s.push(temp);
return MatchRtnCode.UNEXPECTED_SYMBOL;
}
}else if (c==']'){
Character temp=s.pop();
if(temp!='['){
s.push(temp);
return MatchRtnCode.UNEXPECTED_SYMBOL;
}
}else if (c==')'){
Character temp=s.pop();
if(temp!='('){
s.push(temp);
return MatchRtnCode.UNEXPECTED_SYMBOL;
}
}else{
}
}
Character temp = s.pop();
if(temp=='{' || temp=='[' || temp=='('){
return MatchRtnCode.TOO_MANY_OPEN_SYMBOLS;
}else if(temp=='}' || temp==']' || temp==')'){
return MatchRtnCode.TOO_MANY_CLOSED_SYMBOLS;
}else {
return MatchRtnCode.GOOD_STRING;
}
}
}
Stack类是:
import java.util.EmptyStackException;
public interface Stack<E> {
public void push(E data) throws StackFullException;
public E pop() throws EmptyStackException;
public boolean isEmpty() throws EmptyStackException;
}
LLStack类是:
import java.util.EmptyStackException;
public class LLStack<E> implements Stack<E> {
public Node top;
private class Node{
public E data;
public Node next;
public Node(E data, Node next){
this.data=data;
this.next=next;
}
}
public LLStack() {
top = null;
}
@Override
public void push(E data) throws StackFullException {
top=new Node(data, top);
}
@Override
public E pop() throws EmptyStackException {
if(top==null){
throw new EmptyStackException();
}
E data=top.data;
top=top.next;
return data;
}
@Override
public boolean isEmpty() {
return top==null;
}
}
我正在检查一个字符串示例:{[(ab)]}以确保{[(有)}的数量相同。现在它只是打印出EmptyStackError。我该如何解决这个问题?
答案 0 :(得分:0)
if(s.pop()=='{'){
s.pop();
}
pop()改变堆栈的状态。一旦你弹出()并且不需要它,你需要偷看或记得重新开启。
所以试试:
char temp = s.pop();
if(temp != '{') {
s.push(temp);
}
或者只是偷看方法:
public char peek() {
char c = s.pop();
s.push(c);
return c;
}
使用此代替构造if (s.pop() == '}')