1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81  // @Title: 最长回文子串 (Longest Palindromic Substring) // @Author: 15816537946@163.com // @Date: 2020-10-24 11:49:01 // @Runtime: 4 ms // @Memory: 2.1 MB impl Solution { fn expand_center(s: &[char], left: usize, mut right: usize) -> isize { let mut left = left as isize; while left >= 0 && right < s.len() && s[left as usize] == s[right] { left -= 1; right += 1; } right as isize - left as isize - 1 } pub fn longest_palindrome(s: String) -> String { let len = s.len(); if len < 2 { return s; } let s: Vec = s.chars().collect(); let mut start = 0; let mut end = 0; for i in 0..len { let len_odd = Solution::expand_center(&s, i, i); let len_even = Solution::expand_center(&s, i, i + 1); let max_len = len_odd.max(len_even).max(0) as usize; if max_len > end - start { start = i - (max_len - 1) / 2; end = i + max_len / 2; } } s[start..=end].iter().collect() } } /* impl Solution { /* fn helper(s: &str, l: usize, r: usize) -> isize { let mut l = l; let mut r = r; let str_vec: Vec = s.chars().collect(); while l >= 0 && r < s.len() && str_vec[l] == str_vec[r] { l -= 1; r += 1; } r as isize - l as isize - 1 } */ fn helper(s: &str, left: usize, mut right: usize) -> isize { let mut left = left as isize; let str_vec: Vec = s.chars().collect(); while left >= 0 && right < s.len() && str_vec[left as usize] == str_vec[right] { left -= 1; right += 1; } right as isize - left as isize - 1 } pub fn longest_palindrome(s: String) -> String { if s.len() < 2 { return s; } let (mut lo, mut hi) = (0, 0); for i in 0..s.len() { let len1 = Solution::helper(&s, i, i); let len2 = Solution::helper(&s, i, i + 1); let large = len1.max(len2).max(0) as usize; if large > hi - lo { lo = i - (large - 1) >> 1; hi = i + large >> 1; } } String::from(&s[lo..=hi + 1]) } } */