5. Longest Palindromic Substring Leetcode Solution in JavaScript (JS)

0

Table of Contents

Problem:

Given a string s, return the longest 

palindromic

substring in s.

Example 1:

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

Example 2:

Input: s = "cbbd"
Output: "bb"

Constraints:

  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.

Solution:

Simple solution for beginners with separate function to check palindrome and code to create all possible substrings from a string.

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
    let allsubstring = new Array();
    let longestpalindrome = "";
    for(let i = 0; i < s.length;i++){
        
        for(let j = i+1; j < s.length +1 ;j++){
            allsubstring.push(s.slice(i,j));
        }
        
    }
    for(let i = 0; i < allsubstring.length; i++){
        if(ispalindrome(allsubstring[i])){
            if(longestpalindrome.length < allsubstring[i].length){
                longestpalindrome = allsubstring[i];
            }
            
        }
    }
    return longestpalindrome;
};
function ispalindrome(string){
    if(string.length > 2){
         for(let i = 0; i < Math.floor(string.length/2) ; i++){
        if(string[i] != string[string.length -i -1]){
            return false;
        }
    }
    }
    else{
        if(string[1]){
            if(string[1] != string[0]){
                return false;
            }
            
        }
    }
   
    return true;
}

Leave a Comment

Skip to content