1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/problems/rs/longest-palindromic-subsequence.rs
Matej Focko 333866d1bc
chore: split solutions by language
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-06-02 17:19:02 +02:00

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