Skip to content

Commit 68cb57d

Browse files
Update Longest Palindrome Substring.cpp
1 parent 03abc55 commit 68cb57d

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,49 @@
1+
class Solution {
2+
public:
3+
string longestPalindrome(string s) {
4+
int n = s.length();
5+
bool dp[n][n];
6+
7+
int ans = 1;
8+
int st = 0;
9+
10+
///fill all substring of length 1
11+
for(int i=0; i<n; i++){
12+
dp[i][i] = true;
13+
}
14+
15+
///fill all substring of length 2
16+
for(int i=0; i<n-1; i++){
17+
if(s[i] == s[i+1]){
18+
ans = 2;
19+
dp[i][i+1] = true;
20+
st = i;
21+
}
22+
else{
23+
dp[i][i+1] = false;
24+
}
25+
}
26+
27+
//dp[i][j] means start at i and end at j...
28+
///fill the rest of the table
29+
for(int l=3; l<=n; l++){ //for substring of length 3 and more...
30+
for(int i=0; i<=n-l; i++){ //n-l is the max index where index of //particular substring of length l end
31+
int end = i+l-1;
32+
33+
if(s[i] == s[end]){
34+
dp[i][end] = dp[i+1][end-1];
35+
if(dp[i][end] == true){
36+
ans = l;
37+
st = i;
38+
}
39+
}
40+
else{
41+
dp[i][end] = false;
42+
}
43+
}
44+
}
45+
//printing the substring
46+
return s.substr(st, ans);
47+
}
48+
};
149

0 commit comments

Comments
 (0)