Advertisement
Revolucent

Rust is_palindrome

Oct 12th, 2022 (edited)
2,081
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.51 KB | None | 0 0
  1. use unicode_segmentation::UnicodeSegmentation;
  2.  
  3. pub trait Palindrome {
  4.   fn is_palindrome(&self) -> bool;
  5. }
  6.  
  7. impl<N> Palindrome for [N]
  8.   where N: Clone + PartialEq
  9. {
  10.   fn is_palindrome(&self) -> bool {
  11.     if self.is_empty() {
  12.       true
  13.     } else {
  14.       let rev: Vec<N> = self.iter().map(|n| n.clone()).rev().collect();
  15.       &rev == self
  16.     }
  17.   }
  18. }
  19.  
  20. impl Palindrome for str {
  21.   fn is_palindrome(&self) -> bool {
  22.     let rev: String = self.graphemes(true).rev().collect();
  23.     &rev == self
  24.   }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement