如何检查字符串是否平衡?

编程入门 行业动态 更新时间:2024-10-11 09:29:10
本文介绍了如何检查字符串是否平衡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想测试输入String是否平衡.如果有匹配的左,右括号,括号或花括号,则会保持平衡.

I want to test if an input String is balanced. It would be balanced if there is a matching opening and closing parenthesis, bracket or brace.

example: {} balanced () balanced [] balanced If S is balanced so is (S) If S and T are balanced so is ST public static boolean isBalanced(String in) { Stack st = new Stack(); for(char chr : in.toCharArray()) { if(chr == '{') st.push(chr); } return false; }

我在选择做什么时遇到了问题.我是否应该将每个左括号或右括号,方括号或大括号放在堆栈中,然后弹出它们?如果我将它们弹出,那对我有什么帮助?

I'm having problems choosing what to do. Should I put every opening or closing parenthesis, bracket, or brace in a stack then pop them out? If I pop them out, how does that really help me?

推荐答案

1)对于每个左括号:{ [ (将其推入堆栈.

1) For every opening bracket: { [ ( push it to the stack.

2)对于每个右括号:} ] )从堆栈中弹出,并检查括号的类型是否匹配.如果没有返回false;

2) For every closing bracket: } ] ) pop from the stack and check whether the type of bracket matches. If not return false;

即,字符串中的当前符号为},如果从堆栈中弹出的是{中的其他符号,则立即返回false.

i.e. current symbol in String is } and if poped from stack is anything else from { then return false immediately.

3)如果行和堆栈的末尾不为空,则返回false,否则返回true.

3) If end of line and stack is not empty, return false, otherwise true.

更多推荐

如何检查字符串是否平衡?

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

发布评论

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

>www.elefans.com

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