简体   繁体   English

在字符串中查找最长的回文并在 Javascript 中返回最长的单个单词

[英]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.到目前为止,我已经使用 for 循环来做到这一点,但它没有返回正确的单词。

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?谁能给我一个关于我哪里出错的提示?

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.请参考以下代码,您可以使用new Set()和重构代码进一步优化。

 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') )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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