Skip to content

Commit 7089e3e

Browse files
authored
C++ code for longest palindrome substring
1 parent 6c80793 commit 7089e3e

File tree

1 file changed

+41
-0
lines changed
  • DP/Longest Palindrome Substring

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include <iostream>
2+
#include <cstring>
3+
4+
using namespace std;
5+
6+
const int MAX = 1010;
7+
8+
int memo[MAX][MAX];
9+
int lps(const string& s, int i, int j)
10+
{
11+
12+
if (i > j)
13+
return 0;
14+
15+
if (memo[i][j] > -1)
16+
return memo[i][j];
17+
18+
if (s[i] == s[j])
19+
{
20+
int equalCharacters = 2 - (i == j);
21+
return memo[i][j] = equalCharacters + lps(s, i + 1, j - 1);
22+
}
23+
return memo[i][j] = max( lps(s, i + 1, j), lps(s, i, j - 1) );
24+
}
25+
26+
int longest_palindrome(const string& s)
27+
{
28+
29+
memset(memo, -1, sizeof memo);
30+
return lps(s, 0, s.length() - 1);
31+
}
32+
33+
int main()
34+
{
35+
36+
cout << longest_palindrome("bbabcbcab") << '\n';
37+
cout << longest_palindrome("abbaab") << '\n';
38+
cout << longest_palindrome("opengenus") << '\n';
39+
40+
return 0;
41+
}

0 commit comments

Comments
 (0)