[英]While loop crashing browser when requesting data from API with javascript
[英]Browser crashing while loop JavaScript algorithm
伙計們,我正在嘗試編寫一種算法,在該算法中,我傳入一個大字符串,然后讓它循環遍歷字符串,無論找到什么回文,它都會推送到數組中,但是由於某種原因,一旦我進入while循環,我的瀏覽器就會崩潰,我沒有
function arrOfPalindromes(str) {
var palindromeArrays = []
var plength = palindromeArrays.length
// grab first character
// put that in a temp
// continue and look for match
// when match found go up one from temp and down one from index of loop
// if matched continue
// else escape and carry on
// if palendrome push into array
var counter = 0;
for (var i = 0; i < str.length; i++) {
for (var j = 1; j < str.length - 1; j++) {
if (str[i + counter] === str[j - counter]) {
while (str[i + counter] === str[j - counter]) {
console.log(str[j], str[i])
// append the letter to the last index of the array
palindromeArrays[plength] += str[i]
counter++
}
}
}
}
return palindromeArrays
}
var result2 = arrOfPalindromes('asdfmadamasdfbigccbigsdf')
console.log(result2)
不提算法,但條件
while (str[i + counter] === str[j - counter])
使您的代碼崩潰。 當j + counter> str.length返回未定義且與j-counter <0相同時,str [j + counter]有點令人驚訝。 在那里,由於未定義===未定義,因此while循環永遠不會結束。
返回相同大小的數組以處理嵌套的palis。
例如:abxyxZxyxab => 00030703000奇數編號的嵌套palis。
例如:asddsa => 003000偶數為pali。
例如:asdttqwe => 00020000我不知道這是否是巴利語,但在這里我們開始
最小的pali寬度為2個字符,因此我從index:1開始並遞增直到str.len-1
for (var i = 1; i < str.length-1; i++) {
counter=0;
while(str[i]+1-counter == str[i]+counter || str[i]-counter == str[i]+counter) { // always true when counter is 0
// while (even numbered palis || odd numbered palis)
// IF counter is bigger than 0 but we are still here we have found a pali & middle of the pali is i(or i+0.5) &size of the pali is counter*2(or+1)
if(str[i]+1-counter == str[i]+counter){//even sized pali
res[i]=counter*2;
}else{//odd sized pali
res[i]=counter*2+1;
}
counter++;//see if its a bigger pali.
}
}
沒有超級優化,而+ if,else檢查相同的東西。 這些可以以某種方式合並。 甚至偶數和奇數都可以通過任何檢查來處理。
您不需要使用三個循環。 您可以使用兩個for
循環來完成此操作,其中一個從string
的開頭開始,另一個從string
。
在這里,我們使用array
reverse()
方法來匹配回文。
此外,我還添加了其他minLength
參數和重復刪除邏輯,以使其更加美觀。
function findPalindromes(str, minLength) { var palindromes = []; var _strLength = str.length; for (var i = 0; i < _strLength; i++) { for (var j = _strLength - 1; j >= 0; j--) { if (str[i] == str[j]) { var word = str.substring(i, j + 1); //Check if the word is a palindrome if (word === word.split("").reverse().join("")) { //Add minimum length validation and remove duplicates if(word.length >= minLength && palindromes.indexOf(word) === -1){ palindromes.push(word); } } } } } return palindromes; } var result = findPalindromes('asdfmadamasdfbigccbigsdf', 2) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.