试图创建一种检查平衡字符串的方法
这是我的方法的代码,没有给我错误,但在召集它时无法正常工作,任何帮助都将不胜感激:
static boolean isBalanced(String expr) {
Stack stack = new Stack();
for (char ch : expr.toCharArray()) {
if (ch == '{' || ch == '(' || ch == '[') {
stack.push(expr);
} else {
if (expr.isEmpty()) {
return false;
}
char latestOpenedPar = (char) stack.pop();
if (latestOpenedPar == '{' && ch != '}') {
return false;
} else if (latestOpenedPar == '(' && ch != ')') {
return false;
} else if (latestOpenedPar == '[' && ch != ']') {
return false;
}
}
}
return stack.isEmpty();
}
Here is my code for the method, does not give me errors but is not working when calling it out, any help would be appreciated thanks:
static boolean isBalanced(String expr) {
Stack stack = new Stack();
for (char ch : expr.toCharArray()) {
if (ch == '{' || ch == '(' || ch == '[') {
stack.push(expr);
} else {
if (expr.isEmpty()) {
return false;
}
char latestOpenedPar = (char) stack.pop();
if (latestOpenedPar == '{' && ch != '}') {
return false;
} else if (latestOpenedPar == '(' && ch != ')') {
return false;
} else if (latestOpenedPar == '[' && ch != ']') {
return false;
}
}
}
return stack.isEmpty();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果字符串为
“(ABC)”
您将按下(
,然后将其弹出四次,一次为a
,一次b
,c
和)
当然不起作用。另外expr.isempty()
永远不会在循环中返回true,因为如果它是空的,expr.tochararray()
将返回一个零长度的数组,循环将执行零次。使用peek()
在不删除堆栈的情况下查看堆栈的顶部。另外,应将堆栈声明为:
在这种情况下,您无需施放
pop()
或peek()
;它将自动从cartare
到char
自动取代。If the string is
"(abc)"
you are going to push the(
and then pop it four times, once for each ofa
,b
,c
, and)
, which of course will not work. Alsoexpr.isEmpty()
will never return true inside the loop because if it were empty,expr.toCharArray()
would have returned a zero-length array and the loop would execute zero times. Usepeek()
to look at the top of the stack without removing it.Also, your stack should be declared as:
in which case you would not need to cast the value returned by
pop()
orpeek()
; it would be automatically unboxed from aCharacter
to achar
.从问题中不太清楚,但我想您想了解不同的括号是否“一致”。
if(expr.isempty()){return false;}
这是无用的因为如果条件为真,则永远不会输入for loop如果(ch =='{'|| ch =='('|| ch =='['['['){stack.push(expr);}
在这里,您将整个字符串放在堆栈中,将整个字符串作为输入,但是在将stack.pop()
与各种括号进行比较之后,因此可以是stack.push( ch);
stack.pop()
,而无需检查堆栈至少一个元素It is not very clear from the question but I guess you want to understand if the different brackets are "consistent".
if (expr.isEmpty()) {return false;}
this is useless because if the condition were true it would never enter the for loopif (ch == '{' || ch == '(' || ch == '[') {stack.push(expr);}
here you put in the stack the entire string taken as input but after you comparingstack.pop()
with the various brackets, so the right statement can bestack.push(ch);
stack.pop()
without checking that the stack has at least one element