|
| 1 | +// 5. Longest Palindromic Substring, Medium |
| 2 | +// https://leetcode.com/problems/longest-palindromic-substring/ |
| 3 | +impl Solution { |
| 4 | + pub fn longest_palindrome(s: String) -> String { |
| 5 | + let n = s.len(); |
| 6 | + if n <= 1 { |
| 7 | + return s; |
| 8 | + } |
| 9 | + |
| 10 | + let chars = s.chars().collect::<Vec<char>>(); |
| 11 | + |
| 12 | + let mut ans = chars[0].to_string(); |
| 13 | + let mut dp = vec![vec![false; n]; n]; |
| 14 | + for i in 0..n { |
| 15 | + dp[i][i] = true; |
| 16 | + } |
| 17 | + |
| 18 | + let mut max_len = 0; |
| 19 | + for end in 1..n { |
| 20 | + for start in 0..end { |
| 21 | + if chars[start] == chars[end] { |
| 22 | + if end - start == 1 || dp[start + 1][end - 1] { |
| 23 | + dp[start][end] = true; |
| 24 | + if max_len < end - start + 1 { |
| 25 | + max_len = end - start + 1; |
| 26 | + ans = chars[start..=end].iter().collect::<String>(); |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + return ans; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +struct Solution {} |
| 38 | + |
| 39 | +#[cfg(test)] |
| 40 | +mod tests { |
| 41 | + use super::*; |
| 42 | + use crate::{vec_string, vec_vec_i32, vec_vec_string}; |
| 43 | + |
| 44 | + #[test] |
| 45 | + fn test_longest_palindrome() { |
| 46 | + assert_eq!(Solution::longest_palindrome("babad".to_string()), "bab".to_string()); |
| 47 | + } |
| 48 | + |
| 49 | + #[test] |
| 50 | + fn test_longest_palindrome2() { |
| 51 | + assert_eq!(Solution::longest_palindrome("cbbd".to_string()), "bb".to_string()); |
| 52 | + } |
| 53 | + |
| 54 | + #[test] |
| 55 | + fn test_longest_palindrome3() { |
| 56 | + assert_eq!(Solution::longest_palindrome("a".to_string()), "a".to_string()); |
| 57 | + } |
| 58 | + |
| 59 | + #[test] |
| 60 | + fn test_longest_palindrome4() { |
| 61 | + assert_eq!(Solution::longest_palindrome("ac".to_string()), "a".to_string()); |
| 62 | + } |
| 63 | +} |
0 commit comments