匹配括号代码使用堆栈 [英] matching parentheses code using stack
问题描述
我想编写一个程序,以便能够从标准输入接收一个字符串,并检查匹配的括号。这是我的堆栈代码:
I want to write a program to be able to receive a String from the Standard input and Check for matching parentheses. Here is my stack code:
public interface Stack<E>{
public int size();
public boolean isEmpty();
public E top();
public void push(E element);
public E pop()throws EmptyStackException;
}
这是名为MyStack的类,它实现了堆栈:
And this is the class named MyStack which emplements stack:
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;
}
}
/ p>
and this is the main:
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。
But the main code has error in these line: st.push(str.charAt(i));
And if((st.top()==str.charAt(i)))
. the Error is about converting char to String.
可以帮助我解决这些问题吗
can any one please help me to solve these problems??
感谢您提前注意
推荐答案
您应该在main方法中使用一堆字符:
You should use a stack of characters in your main method:
Stack<Character> st = new myStack<>();
一旦你得到它编译,你也会发现一些错误与你的逻辑。例如,当你读取)
时,在(aa)
表达式中你有 code>在堆栈上,所以你不能只是比较,但需要考虑到这一点。
Once you get it to compile you will also find some mistakes with your logic. For example in the expression (aa)
when you read the )
you have (
on the stack, so you cannot just compare, but need to account for that.
这篇关于匹配括号代码使用堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!