Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find the longest palindrome in a string. #Rust #Polindrome
use std::collections::HashMap;
pub fn longest_palindrome(s: String) -> String {
let mut poly: HashMap<&str, usize> = Default::default();
for substr in s.split(" ") {
let len = substr.len();
let mid = (len / 2) as usize;
if substr[0..mid] == substr[mid..len].chars().rev().collect::<String>() {
poly.insert(substr, len);
}
}
let mut max = ("", 0);
'sort: for (k, v) in poly {
if max.1 < v {
max = (k, v);
continue 'sort;
}
}
max.0.to_string()
}
fn main() {
assert_eq!(
longest_palindrome("abba sad asd fasdf sadf adddda sfsd".to_string()),
"adddda".to_string()
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment