|
| 1 | +// Brute Force |
| 2 | +pub fn longest_palindrome(input: &str) -> &str { |
| 3 | + let length = input.len(); |
| 4 | + let mut sub: &str; |
| 5 | + for i in 0..length { |
| 6 | + for j in 0..i + 1 { |
| 7 | + sub = &input[j..length - i + j]; |
| 8 | + if is_palindrome(sub.to_string()) { |
| 9 | + return sub; |
| 10 | + } |
| 11 | + } |
| 12 | + } |
| 13 | + return &input[0..0]; |
| 14 | +} |
| 15 | + |
| 16 | +pub fn is_palindrome(s: String) -> bool { |
| 17 | + let mut rs = s.clone().into_bytes(); |
| 18 | + rs.reverse(); |
| 19 | + return rs == s.into_bytes(); |
| 20 | +} |
| 21 | + |
| 22 | +#[cfg(test)] |
| 23 | +mod test { |
| 24 | + use super::is_palindrome; |
| 25 | + use super::longest_palindrome; |
| 26 | + |
| 27 | + #[test] |
| 28 | + fn test_is_palindrome() { |
| 29 | + assert_eq!(is_palindrome(String::from("aba")), true); |
| 30 | + assert_eq!(is_palindrome(String::from("ab")), false); |
| 31 | + assert_eq!(is_palindrome(String::from("a")), true); |
| 32 | + assert_eq!(is_palindrome(String::from("abab")), false); |
| 33 | + } |
| 34 | + |
| 35 | + #[test] |
| 36 | + fn test_longest_palindrome() { |
| 37 | + assert_eq!(longest_palindrome("babad"), "bab"); |
| 38 | + assert_eq!(longest_palindrome("abccba"), "abccba"); |
| 39 | + assert_eq!(longest_palindrome("cabccbad"), "abccba"); |
| 40 | + assert_eq!(longest_palindrome("xbacabccbaddab"), "abccba"); |
| 41 | + assert_eq!(longest_palindrome("abccbaddxe"), "abccba"); |
| 42 | + assert_eq!(longest_palindrome("ddxeabccba"), "abccba"); |
| 43 | + } |
| 44 | +} |
0 commit comments