|
| 1 | +use std::ops::RangeInclusive; |
| 2 | +pub struct Solution {} |
| 3 | +impl Solution { |
| 4 | + pub fn longest_palindrome(s: String) -> String { |
| 5 | + let s = s.as_str(); |
| 6 | + (0..s.len()) |
| 7 | + .fold("", |current_longest, idx| { |
| 8 | + current_longest |
| 9 | + .longest(s.longest_palindrome_around(idx..=idx)) |
| 10 | + .longest(s.longest_palindrome_around(idx..=idx + 1)) |
| 11 | + }) |
| 12 | + .into() |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +trait LongestPalindrome { |
| 17 | + type Idx; |
| 18 | + fn longest_palindrome_around(&self, center: RangeInclusive<Self::Idx>) -> &Self; |
| 19 | + fn longest<'a>(&'a self, other: &'a Self) -> &'a Self; |
| 20 | +} |
| 21 | +impl LongestPalindrome for str { |
| 22 | + type Idx = usize; |
| 23 | + fn longest_palindrome_around(&self, center: RangeInclusive<Self::Idx>) -> &Self { |
| 24 | + let (mut start, mut end) = center.into_inner(); |
| 25 | + let characters = self.as_bytes(); |
| 26 | + loop { |
| 27 | + if characters.get(start) != characters.get(end) { |
| 28 | + return &self[start + 1..end]; |
| 29 | + } |
| 30 | + if let (Some(new_start), Some(new_end)) = (start.checked_sub(1), end.checked_add(1)) { |
| 31 | + start = new_start; |
| 32 | + end = new_end; |
| 33 | + } else { |
| 34 | + return &self[start..=end]; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + fn longest<'a>(&'a self, other: &'a Self) -> &'a Self { |
| 39 | + if self.len() > other.len() { |
| 40 | + self |
| 41 | + } else { |
| 42 | + other |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments