2108. 找出数组中的第一个回文字符串 Find First Palindromic String in the Array
这道题与 0125. 验证回文串 Valid Palindrome 基本一致, 只是多了一个循环遍历, 将不再讲解.
靠拢型双指针
#![allow(unused)] fn main() { // 双指针法 pub fn first_palindrome1(words: Vec<String>) -> String { fn is_palindrome(s: &str) -> bool { let bytes = s.as_bytes(); let mut left = 0; let mut right = bytes.len() - 1; while left < right { if bytes[left] != bytes[right] { return false; } left += 1; right -= 1; } true } for word in &words { if is_palindrome(word) { return word.clone(); } } String::new() } }
反转字符串
#![allow(unused)] fn main() { // 反转字符串 pub fn first_palindrome2(words: Vec<String>) -> String { fn is_palindrome(s: &str) -> bool { s.chars().rev().collect::<String>() == s } for word in &words { if is_palindrome(word) { return word.clone(); } } String::new() } }