匹配括号代码使用堆栈

编程入门 行业动态 更新时间:2024-10-09 23:13:04
本文介绍了匹配括号代码使用堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

匹配括号代码使用堆栈

本文发布于:2023-11-29 02:30:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644943.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:堆栈   括号   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!