Skip to content

Commit

Permalink
Longest palindromic Substring Code Added
Browse files Browse the repository at this point in the history
  • Loading branch information
chetan-2002 committed Oct 23, 2022
1 parent cd312d0 commit d633401
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions leetcode/LongestPalindromicSubstring.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Longest Palindromic Substring - LeetCode Problem 5
// https://leetcode.com/problems/longest-palindromic-substring/

class Solution
{
public:
string longestPalindrome(string s)
{
int n = s.size();
int start;
int length;
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int gap = 0; gap < n; gap++)
{
for (int i = 0, j = gap; j < n; i++, j++)
{
if (gap == 0)
{
dp[i][j] = 1;
}
else if (gap == 1)
{
if (s[i] == s[j])
{
dp[i][j] = 2;
}
}
else
{
if (s[i] == s[j] && dp[i + 1][j - 1] > 0)
{
dp[i][j] = 2 + dp[i + 1][j - 1];
}
}
if (dp[i][j] > 0)
{
start = i;
length = dp[i][j];
}
}
}
return s.substr(start, length);
}
};

0 comments on commit d633401

Please sign in to comment.