|
| 1 | +/** |
| 2 | + * [5] Longest Palindromic Substring |
| 3 | + * |
| 4 | + * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. |
| 5 | + * |
| 6 | + * Example 1: |
| 7 | + * |
| 8 | + * |
| 9 | + * Input: "babad" |
| 10 | + * Output: "bab" |
| 11 | + * Note: "aba" is also a valid answer. |
| 12 | + * |
| 13 | + * |
| 14 | + * Example 2: |
| 15 | + * |
| 16 | + * |
| 17 | + * Input: "cbbd" |
| 18 | + * Output: "bb" |
| 19 | + * |
| 20 | + * |
| 21 | + */ |
| 22 | +pub struct Solution {} |
| 23 | + |
| 24 | +// submission codes start here |
| 25 | + |
| 26 | +impl Solution { |
| 27 | + pub fn longest_palindrome(s: String) -> String { |
| 28 | + let seq: Vec<char> = s.chars().collect(); |
| 29 | + let len = seq.len(); |
| 30 | + if len < 1 {return s} |
| 31 | + let (mut idx, mut curr_len, mut curr_start, mut curr_end) = (0, 0, 0, 0); |
| 32 | + while idx < len { |
| 33 | + let (mut i, mut j) = (idx, idx); |
| 34 | + let ch = seq[idx]; |
| 35 | + // handle same char |
| 36 | + while i > 0 && seq[i - 1] == ch { i -= 1 }; |
| 37 | + while j < len - 1 && seq[j + 1] == ch { j += 1 }; |
| 38 | + idx = j + 1; |
| 39 | + while i > 0 && j < len - 1 && seq[i - 1] == seq[j + 1] { |
| 40 | + i -= 1; j +=1; |
| 41 | + } |
| 42 | + let max_len = j - i + 1; |
| 43 | + if max_len > curr_len { |
| 44 | + curr_len = max_len; curr_start = i; curr_end = j; |
| 45 | + } |
| 46 | + if max_len >= len - 1 { |
| 47 | + break; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + s[curr_start..curr_end+1].to_owned() |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +// submission codes end |
| 56 | + |
| 57 | +#[cfg(test)] |
| 58 | +mod tests { |
| 59 | + use super::*; |
| 60 | + |
| 61 | + #[test] |
| 62 | + fn test_5() { |
| 63 | + assert_eq!(Solution::longest_palindrome("aaaaa".to_owned()), "aaaaa"); |
| 64 | + assert_eq!(Solution::longest_palindrome("babab".to_owned()), "babab"); |
| 65 | + assert_eq!(Solution::longest_palindrome("babcd".to_owned()), "bab"); |
| 66 | + assert_eq!(Solution::longest_palindrome("cbbd".to_owned()), "bb"); |
| 67 | + assert_eq!(Solution::longest_palindrome("bb".to_owned()), "bb"); |
| 68 | + assert_eq!(Solution::longest_palindrome("".to_owned()), ""); |
| 69 | + } |
| 70 | +} |
0 commit comments