Skip to content

Longest Palindromic Substring #1489

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Dynamic-Programming/LongestPalindromicSubstring.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
LeetCode -> https://leetcode.com/problems/longest-palindromic-substring

Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.

*/
/**
* Finds the longest palindromic substring
* @param {string} s Input string
* @returns {string} Longest Palindromic Substring
*/
function longestPalindrome(s) {
const n = s.length;
const dp = new Array(n + 1).fill(0).map(() => new Array(n + 1).fill(0));
const len = new Array(n + 1).fill(0).map(() => new Array(n + 1).fill(0));
let str = "";
let mx = 0;
//fill for single character
for (let i = 0; i < n; i++) {
dp[i][i] = 1;
len[i][i] = 1;
}

for (let i = n - 2; i >= 0; i--) {
for (let j = i + 1; j < n; j++) {
if (s[i] === s[j] && j - i === 1) {
len[i][j] = 2;
dp[i][j] = 1;
} else if (s[i] === s[j] && dp[i + 1][j - 1]) {
dp[i][j] = 1;
len[i][j] = j - i + 1;
}
}
}

for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (len[i][j] > mx && dp[i][j]) {
mx = len[i][j];
str = s.substring(i, j + 1);
}
}
}

return str;
}