-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathpalindrome_longest_subsequence.cpp
53 lines (46 loc) · 1.21 KB
/
palindrome_longest_subsequence.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
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Description: Find longest length palindromic subsequence in s[i..j]
* Usage: See below O(V^2)
* Source: https://github.com/dragonslayerx
*/
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
using namespace std;
void process(const string &s, int last[][30]) {
int n = s.size();
for (int j = 0; j < 26; j++) {
if (j==s[0]-'a') {
last[0][j] = 0;
} else {
last[0][j] = -1;
}
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < 26; j++) {
last[i][j] = last[i-1][j];
}
last[i][s[i]-'a'] = i;
}
}
int last[1005][30];
int dp[1005][1005];
int main() {
string s;
cin >> s;
int len = s.size();
process(s, last);
memset(dp, 0, sizeof(dp));
for (int i = 0; i < len; i++) dp[i][i] = 1;
for (int i = len-1; i >= 0; i--) {
for (int j = i+1; j < len; j++) {
dp[i][j] = 1;
dp[i][j] = max(dp[i][j], dp[i+1][j]);
if (last[j][s[i]-'a'] > i) {
dp[i][j] = max(dp[i][j], 2 + dp[i+1][last[j][s[i]-'a']-1]);
}
}
}
cout << dp[0][len-1] << endl;
}