Search code examples
javascriptfor-looppalindrome

Finding the longest Palindrome in a string and returning the longest single word in Javascript


I writing a method to find the longest palindrome in a sentence of words. So far I have used the for loop to do this but its not returning the correct word.

function findLongestPalindrome(sentence) {
  let wordArray = sentence.split(" ");
  let longestWord = 0;
  let word = " ";
  
  for(let i = 0; i < wordArray.length; i++) {
    if(longestWord < wordArray[i].length) {
      longestWord = wordArray[i].length;
      word = wordArray[i]
    }
  }
  return word;
}

Can anyone give me a tip on where I am going wrong?


Solution

  • You are missing a function to check string is palindrome or not. Please refer the below code and you can further optimize using new Set() and refactoring the code.

    function findLongestPalindrome(sentence) {
      let wordArray = sentence.match(/\b\w+\b/g),
          longestWord = 0,
          word = " ";
    
      for (let i = 0; i < wordArray.length; i++) {
        if (longestWord < wordArray[i].length && isPalindrome(wordArray[i])) {
          longestWord = wordArray[i].length;
          word = wordArray[i]
        }
      }
      
      return word;
    }
    
    function isPalindrome(str) {
      return str.split('').reverse().join('') === str;
    }
    
    console.log(
      findLongestPalindrome('This is an interesting sentence: kayak, november, anna')
    )