Sayooj V R
Sayooj V R

Reputation: 2363

Largest possible palindromic substring of a given string in JavaScript

This is an interview question which I was asked to write. The time complexity should be small. I couldn't write a proper solution for this problem.

Question : Largest possible palindromic substring of a given string in JavaScript

Upvotes: 0

Views: 154

Answers (1)

Deepak Tatyaji Ahire
Deepak Tatyaji Ahire

Reputation: 5321

Kindly go through the following code:

var longestPalindrome = function(string) {

  var length = string.length;
  var result = "";

  var centeredPalindrome = function(left, right) {
    while (left >= 0 && right < length && string[left] === string[right]) {
      //expand in each direction.
      left--;
      right++;
    }

    return string.slice(left + 1, right);
  };

  for (var i = 0; i < length - 1; i++) {
    var oddPal = centeredPalindrome(i, i + 1);

    var evenPal = centeredPalindrome(i, i);

    if (oddPal.length > 1)
      console.log("oddPal: " + oddPal);
    if (evenPal.length > 1)
      console.log("evenPal: " + evenPal);

    if (oddPal.length > result.length)
      result = oddPal;
    if (evenPal.length > result.length)
      result = evenPal;
  }
  return "the palindrome is: " + result + " and its length is: " + result.length;
};

console.log(
  longestPalindrome("nan noon is redder")
);

Credits: @Paul Roub

Upvotes: 1

Related Questions