-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path516.cpp
More file actions
25 lines (25 loc) · 706 Bytes
/
516.cpp
File metadata and controls
25 lines (25 loc) · 706 Bytes
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
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
if(n<2)
return n;
vector<vector<int>> dp(n,vector<int>(n,0));
for(int i=0;i<n; i++){
dp[i][i] = 1;
}
int res = 1;
for(int length = 2; length<=n; length++){
for(int i=0; i<n-length+1; i++){
int j = i+length-1;
if(length==2 && s[i] == s[j])
dp[i][j] = 2;
else if(s[i]==s[j])
dp[i][j] = dp[i+1][j-1]+2;
else
dp[i][j] = max(dp[i+1][j],dp[i][j-1]);
}
}
return dp[0][n-1];
}
};