[英]Cannot come up with why does my Java code loop infinitely
I tried to do this LeetCode daily challenge but I've found out that my code loops infinitely.我试着做这个 LeetCode 每日挑战,但我发现我的代码无限循环。
I looked through it multiple times, but I cannot find where the problem is.我多次查看它,但我找不到问题所在。 If anyone could spot it, please answer.如果有人能看出来,请回答。
public int longestValidParentheses(String s) {
int count, highestOne = 0, index = 0;
boolean isSevered = false;
boolean theEnd = false;
while(!theEnd) {
count = 0;
while(!isSevered) {
if(index<s.length()-2) {
if(s.charAt(index) == '(' & s.charAt(index++) == ')') {count = count + 2;index = index+2;}
else {isSevered = true;}}
else theEnd=true;isSevered=true;
}
highestOne = count;
}
return highestOne;
}
I have 2 suggestions for you:我有2条建议给你:
So you have 2 mistakes here that make your code run for infinity:因此,您在这里有 2 个错误使您的代码无限运行:
isSevered
will always be true after one loop exactly, as you change it to true no matter what happens as it is outside the if else statements, hence the reason I wrote the 2 advices above. isSevered
在一个循环之后将始终为真,因为无论发生什么都将其更改为真,因为它在 if else 语句之外,因此我写了上面的 2 个建议。isSeveres
or theEnd
at the outside loop.您永远不会在外部循环中更改isSeveres
或theEnd
。 Meaning that if isSevers
is true and theEnd
is false, you will never enter the internal while
and will never exit the outside while
.这意味着如果isSevers
为 true 而theEnd
为 false,您将永远不会进入内部while
并且永远不会退出外部while
。 The two of those combined means that if the condition that make theEnd
be initialized with true won't happen at the first run, you will be stuck with infinity loop.这两者的结合意味着如果使theEnd
初始化为 true 的条件不会在第一次运行时发生,那么您将陷入无限循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.