problems(rs): add “516. Longest Palindromic Subsequence”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
2c3aa74565
commit
01b25b0ffe
1 changed files with 45 additions and 0 deletions
45
problems/longest-palindromic-subsequence.rs
Normal file
45
problems/longest-palindromic-subsequence.rs
Normal 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);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue