45 lines
1 KiB
Rust
45 lines
1 KiB
Rust
use std::cmp;
|
|
|
|
struct Solution {}
|
|
impl Solution {
|
|
pub fn longest_palindrome_subseq(s: String) -> i32 {
|
|
let mut longest: Vec<Vec<i32>> = vec![];
|
|
longest.resize_with(s.len(), || {
|
|
let mut nested: Vec<i32> = vec![];
|
|
nested.resize(s.len(), 0);
|
|
|
|
nested
|
|
});
|
|
|
|
for i in (0..s.len()).rev() {
|
|
longest[i][i] = 1;
|
|
|
|
for j in i + 1..s.len() {
|
|
if s.as_bytes()[i] == s.as_bytes()[j] {
|
|
longest[i][j] = 2 + longest[i + 1][j - 1];
|
|
} else {
|
|
longest[i][j] = cmp::max(longest[i + 1][j], longest[i][j - 1]);
|
|
}
|
|
}
|
|
}
|
|
|
|
longest[0][s.len() - 1]
|
|
}
|
|
}
|
|
|
|
fn main() {}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn with_skip() {
|
|
assert_eq!(Solution::longest_palindrome_subseq("bbbab".to_owned()), 4);
|
|
}
|
|
|
|
#[test]
|
|
fn without_skip() {
|
|
assert_eq!(Solution::longest_palindrome_subseq("cbbd".to_owned()), 2);
|
|
}
|
|
}
|