1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

problems(rs): add “516. Longest Palindromic Subsequence”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-04-14 22:40:09 +02:00
parent 2c3aa74565
commit 01b25b0ffe
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,45 @@
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);
}
}