[英]Cannot come up with why does my Java code loop infinitely
我試着做這個 LeetCode 每日挑戰,但我發現我的代碼無限循環。
我多次查看它,但我找不到問題所在。 如果有人能看出來,請回答。
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;
}
我有2條建議給你:
因此,您在這里有 2 個錯誤使您的代碼無限運行:
isSevered
在一個循環之后將始終為真,因為無論發生什么都將其更改為真,因為它在 if else 語句之外,因此我寫了上面的 2 個建議。isSeveres
或theEnd
。 這意味着如果isSevers
為 true 而theEnd
為 false,您將永遠不會進入內部while
並且永遠不會退出外部while
。 這兩者的結合意味着如果使theEnd
初始化為 true 的條件不會在第一次運行時發生,那么您將陷入無限循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.