简体   繁体   中英

Understanding NESTED FOR loops in javascript and palindrome

Currently I am trying to solve a problem with a nested for loop. I have solved it using the reverse method before. Now I am given it a go with a nest for loop.

I am confused on why my code doesn't work. Would love and appreciate some guidance. Thanks in advance.

 function palindrome(str) { var splitStr = str.split(""); for(var x = 0; x < splitStr.length; x++){ for(var j = splitStr.length-1; j >= 0; j--){ if(splitStr[x] === splitStr[j]){ return true; } } return false; } } palindrome("racecar"); 

The reason your code is not working is you are trying to compare character from your array with each character from the array in reverse order. For string racecar , first r is getting compared with each character in racecar in reverse order.

Also, you are returning as soon as your first comparison succeed.

You don't require two loops. This could be accomplished using one loop.

  • Your for loop should begin with 0 index to half of length of string.
  • Compare the character at that index with length of string minus one minus that index.
  • In case, any character don't match, break out of loop.
  • Otherwise, continue comparison.
  • Once your reach till the half of length of your string, you have a palindrome.

 function palindrome(str) { var splitStr = str.split(""); var isPalindrome = true; for(var x = 0; x <= splitStr.length / 2; x++){ if(splitStr[x] !== splitStr[splitStr.length - 1 - x]){ isPalindrome = false; break; } } return isPalindrome; } console.log(palindrome("racecar")); console.log(palindrome("foobar")); 

Alternatively, you can reverse the string and compare the value of original string with the reversed string.

 var palindrome = function(str) { return str === str.split('').reverse().join(''); } console.log(palindrome("racecar")); console.log(palindrome("foobar")); 

Think about what the two loops will be doing when executed. For example with a 3-letter word, the indices will be like this:

x == 0, j == 2
x == 0, j == 1
x == 0, j == 0
x == 1, j == 2
x == 1, j == 1
x == 1, j == 0
x == 2, j == 2
x == 2, j == 1
x == 2, j == 0

See the problem?

Additionally, you will return true if any match is true. The condition should be the opposite, it should return false if any match is false (and only return true if all matches are successful).

you can't use two for loop like this, becouse in your example racecar . if first time i=0 and j=splitStr.length-1 both are r so it return true in very first time an exit the loop. some times other letters not a palindrome letter. so that is the error. and you can't check with nested for loop like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM