Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

LongestPalindromicSubstring #1486

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

Closed
ZainabMalik5 wants to merge 3 commits into TheAlgorithms:master from ZainabMalik5:newbranch3
Closed
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
42 changes: 42 additions & 0 deletions Dynamic-Programming/LongestPalindromicSubstring.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
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.

*/
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 chracter
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;
}

AltStyle によって変換されたページ (->オリジナル) /