Longest Palindrome substring

0

0

pavan koka

The code creates a function that takes a string and returns the longest palindrome. It uses a variable, longestPalindrome, to store the length of the palindrome. The code first splits the string into an array of words. For each word, it creates an empty object, and assigns a value to each of the properties. For example, the property for index 1 would have a value of 1, and the property for index 2 would have a value of 2. Next, the code loops through the string, and for each word, it checks to see if the word is the same as the previous word. If it is, the value for the property for that word is set to 1. If the word is not the same as the previous word, the value for the property is set to 0. Finally, the code returns the string with the value of the longest palindrome stored at the position of the leftmost word and the length of the longest palindrome stored at the position of the rightmost word.

``````var longestPalindrome = function(s) {
const dp = {}
s.split('').forEach((el, index) => {
dp[index] = {}
dp[index][index] = 1
})
let left=0, right=0;
for(let i=1; i<s.length; i++) {
for(let j=0; j<s.length-i; j++) {
if(i === 1) {
if(s[j] == s[j+i]) {
dp[j][j+i] = 2;
} else {
dp[j][j+i] = 0;
}
} else {
if(s[j] == s[j+i]) {
dp[j][j+i] = dp[j+1][j+i-1] ? 2 + dp[j+1][j+i-1] : 0;
} else {
dp[j][j+i] = 0;
}
}
if(dp[j][j+i] > right-left+1) {
right = j+i;
left = j;
}
}
}
return s.substring(left, right+1)
};``````
• Rulesets
• Playground
• Snippets
• Cookbooks
Support

We are SOC-2 Compliance Certified