forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLPS.cpp
41 lines (30 loc) · 758 Bytes
/
LPS.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <cstring>
using namespace std;
const int MAX = 1010;
int memo[MAX][MAX];
int lps(const string& s, int i, int j)
{
if (i > j)
return 0;
if (memo[i][j] > -1)
return memo[i][j];
if (s[i] == s[j])
{
int equalCharacters = 2 - (i == j);
return memo[i][j] = equalCharacters + lps(s, i + 1, j - 1);
}
return memo[i][j] = max( lps(s, i + 1, j), lps(s, i, j - 1) );
}
int longest_palindrome(const string& s)
{
memset(memo, -1, sizeof memo);
return lps(s, 0, s.length() - 1);
}
int main()
{
cout << longest_palindrome("bbabcbcab") << '\n';
cout << longest_palindrome("abbaab") << '\n';
cout << longest_palindrome("opengenus") << '\n';
return 0;
}