Skip to content

Commit 1c0fcf3

Browse files
Create Longest-Palindromic-Substring.cpp
1 parent acb84fc commit 1c0fcf3

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Question Link : https://leetcode.com/problems/longest-palindromic-substring/
2+
3+
class Solution {
4+
public:
5+
string longestPalindrome(string s) {
6+
int n = s.size();
7+
int dp[n][n];
8+
9+
memset(dp,0,sizeof(dp));
10+
int end=1;
11+
int strt=0;
12+
13+
for(int i=0;i<n;i++){
14+
dp[i][i] = 1;
15+
}
16+
for(int i=0;i<n-1;i++){
17+
if(s[i]==s[i+1]){
18+
dp[i][i+1]=1;
19+
strt=i;end=2;
20+
}
21+
}
22+
for(int j=2;j<n;j++){
23+
for(int i=0;i< n-j;i++){
24+
int lft=i;
25+
int rght = i+j;
26+
27+
if(dp[lft+1][rght-1]==1 && s[lft]==s[rght])
28+
{
29+
dp[lft][rght]=1; strt=i; end=j+1;
30+
}
31+
}
32+
}
33+
return s.substr(strt, end);
34+
}
35+
};

0 commit comments

Comments
 (0)