From 85f17ff6f08702772a9560dfc7110149c3a0e30e Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 3 Feb 2025 11:26:28 +0800 Subject: [PATCH] 20250203 finished. --- src/problem/mod.rs | 2 + src/problem/p680_valid_palindrome_ii.rs | 53 +++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 src/problem/p680_valid_palindrome_ii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 1979ff7..61e8d0c 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -466,3 +466,5 @@ mod p541_reverse_string_ii; mod p81_search_in_rotated_sorted_array_ii; mod p598_range_addition_ii; + +mod p680_valid_palindrome_ii; diff --git a/src/problem/p680_valid_palindrome_ii.rs b/src/problem/p680_valid_palindrome_ii.rs new file mode 100644 index 0000000..a882630 --- /dev/null +++ b/src/problem/p680_valid_palindrome_ii.rs @@ -0,0 +1,53 @@ +/** + * [680] Valid Palindrome II + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn valid_palindrome(s: String) -> bool { + let s: Vec = s.chars().collect(); + let length = s.len(); + + for i in 0..length / 2 { + if s[i] != s[s.len() - 1 - i] { + // 这B玩意儿还带回溯的 + // 需要选择从左边删还是从右边删 + // 这里直接强制一下 + return Self::check_palindrome(&s[i + 1..s.len() - i]) + || Self::check_palindrome(&s[i..s.len() - 1 - i]); + } + } + + true + } + + fn check_palindrome(s: &[char]) -> bool { + for i in 0..s.len() / 2 { + if s[i] != s[s.len() - 1 - i] { + return false; + } + } + + true + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_680() { + assert!(Solution::valid_palindrome( + "cupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupucu".to_owned() + )); + assert!(Solution::valid_palindrome("cbbcc".to_owned())); + assert!(Solution::valid_palindrome("aba".to_owned())); + assert!(Solution::valid_palindrome("abca".to_owned())); + assert!(!Solution::valid_palindrome("abc".to_owned())); + } +}