From 88ea0ab1b7ceb164873ceb594442ae2f70e54c86 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 5 Mar 2025 11:59:54 +0800 Subject: [PATCH] 20250305 finished. --- src/problem/mod.rs | 2 + src/problem/p1328_break_a_palindrome.rs | 50 +++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 src/problem/p1328_break_a_palindrome.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 82455a5..eaf1f30 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -518,3 +518,5 @@ mod p132_palindrome_partitioning_ii; mod p1278_palindrome_partitioning_iii; mod p1745_palindrome_partitioning_iv; + +mod p1328_break_a_palindrome; diff --git a/src/problem/p1328_break_a_palindrome.rs b/src/problem/p1328_break_a_palindrome.rs new file mode 100644 index 0000000..f78f3a6 --- /dev/null +++ b/src/problem/p1328_break_a_palindrome.rs @@ -0,0 +1,50 @@ +/** + * [1328] Break a Palindrome + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn break_palindrome(palindrome: String) -> String { + if palindrome.len() == 1 { + return "".to_owned(); + } + + let mut s: Vec = palindrome.chars().collect(); + + let mut flag = false; + for i in 0..s.len() / 2 { + if s[i] != 'a' { + s[i] = 'a'; + flag = true; + break; + } + } + + // 说明s的前半段全部都是a + // 直接把最后一个字符改成b + if !flag { + let pos = s.len() - 1; + s[pos] = 'b'; + } + + s.into_iter().collect() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1328() { + assert_eq!("aabab", Solution::break_palindrome("aabaa".to_owned())); + assert_eq!("ab", Solution::break_palindrome("aa".to_owned())); + assert_eq!("ab", Solution::break_palindrome("bb".to_owned())); + assert_eq!("aaccba", Solution::break_palindrome("abccba".to_owned())); + assert_eq!("", Solution::break_palindrome("a".to_owned())); + } +}