1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00
LeetCode/rs/longest-palindromic-subsequence.rs

46 lines
1 KiB
Rust
Raw Normal View History

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);
}
}