使用堆栈匹配括号代码

时间:2013-11-08 17:16:27

标签: java string char

我想编写一个程序,以便能够从标准输入接收字符串并检查匹配的括号。这是我的堆栈代码:

    public interface Stack<E>{
    public int size();
    public boolean isEmpty();
    public E top();
    public void push(E element);
    public E pop()throws EmptyStackException;
    }

这是名为MyStack的类,它实现了堆栈:

    public  class myStack<E> implements Stack<E>{
    private final E s[];
    int t=0;
    public myStack() {
    this.s = (E[]) new Object[100];
    }
    public int size(){
    return t;
    }

    public boolean isEmpty(){
    switch(size()){
        case 0:
            return true;
    }
    return false;
    }

    public E top() {
    if(isEmpty())
        throw new EmptyStackException();
    return s[t-1];
    }


    public void push(E element) {
     if(isEmpty())
        s[0]= element;
     else
        s[t]= element;
     t++;
    }
    public E pop() {
    E x;
    if(isEmpty())
        throw new EmptyStackException();
    else{
        x = s[t-1];
        s[t-1] = null;
        t--;
    }
    return x;
    }

    }

这是主要的:

      public static void main(String[] args) {

      Stack<String> st=new myStack<>(); 
      Scanner s = new Scanner(System.in);
      String str;
      str = s.nextLine();
      for(int i=0;i<str.length();i++)
      {
        if((str.charAt(i)=='{')||(str.charAt(i)=='(')||(str.charAt(i)=='['))
        {
            st.push(str.charAt(i));
        }
        else if((str.charAt(i)=='}')||(str.charAt(i)==')')||(str.charAt(i)==']'))
            if((st.top()==str.charAt(i)))
                    st.pop();
            else 
            {
                System.out.println("Error");
                System.exit(0);
            }
     }


     if(st.isEmpty())
        System.out.println("True");
     else
        System.out.println("True");
     }

但主要代码在这些行中有错误:st.push(str.charAt(i));if((st.top()==str.charAt(i)))。错误是关于将char转换为String。

任何人都可以帮我解决这些问题吗?

抱歉,我知道这长代码很无聊但我真的需要解决这个问题

感谢你提前注意

2 个答案:

答案 0 :(得分:2)

您应该在main方法中使用一堆字符:

Stack<Character> st = new myStack<>();

一旦你完成编译,你也会发现你的逻辑有些错误。例如,在表达式(aa)中,当您在堆栈上阅读) (时,您不能仅仅进行比较,而是需要考虑到这一点。

答案 1 :(得分:1)

我在这里看到两个选项。第一个是陈述,并使用一堆字符。另一种方法是将char转换为Character,然后在推送到堆栈之前调用.toString()方法。

你的推动看起来像是:

st.push(((Character)str.charAt(i)).toString());

和你的pop:

if((st.top().equals(((Character)str.charAt(i)).toString()))
    st.pop();

您可能必须使用.equals(Object)方法来正确确定字符串/字符是否相等。 ==只会在某些情况下查看引用,这些引用在引用到内存中的不同位置时将返回false,即使字符串的内容相同。

如果您将堆栈专门用作其他地方的字符串,我会将其保留为字符串,否则只使用一堆字符就更清晰了

Stack<Character> st = new myStack<>();

Stack<char> st = new myStack<>();
相关问题