Skip to main content

rustgym/leetcode/
_516_longest_palindromic_subsequence.rs

1struct Solution;
2use std::i32;
3
4impl Solution {
5    fn longest_palindrome_subseq(s: String) -> i32 {
6        let s: Vec<char> = s.chars().collect();
7        let n = s.len();
8        let mut dp: Vec<Vec<i32>> = vec![vec![0; n + 1]; n];
9        for i in 0..n {
10            dp[i][i + 1] = 1;
11        }
12        for w in 2..=n {
13            for i in 0..=n - w {
14                let j = i + w;
15                if s[i] == s[j - 1] {
16                    dp[i][j] = 2 + dp[i + 1][j - 1];
17                } else {
18                    dp[i][j] = i32::max(dp[i + 1][j], dp[i][j - 1]);
19                }
20            }
21        }
22        dp[0][n]
23    }
24}
25
26#[test]
27fn test() {
28    let s = "bbbab".to_string();
29    let res = 4;
30    assert_eq!(Solution::longest_palindrome_subseq(s), res);
31    let s = "cbbd".to_string();
32    let res = 2;
33    assert_eq!(Solution::longest_palindrome_subseq(s), res);
34}