Skip to content

Instantly share code, notes, and snippets.

@nkhil
Last active September 14, 2020 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkhil/8a2d5306ef1adc0a32282a4a78385e96 to your computer and use it in GitHub Desktop.
Save nkhil/8a2d5306ef1adc0a32282a4a78385e96 to your computer and use it in GitHub Desktop.
Given a string, find the longest palindrome (JavaScript)

Find the longest palindrome (JavaScript)

This is my solution to the longest palindrome kata on Code Wars.

Solution

  function reverseString(st) {
    return st.split('').reverse().join('')
  }

function longestPalindrome(s) {
  const str = s.toLowerCase()

  let palindrome = ''

  for (let i = 0; i < str.length; i++) {
    for (let j = i + 1; j <= str.length; j++) {
      const currentWord = str.substring(i, j)
      const reversedWord = reverseString(currentWord)
      if (currentWord === reversedWord && currentWord.length > palindrome.length) {
        palindrome = currentWord
      }
    }
  }
  return palindrome.length
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment