Skip to content

Instantly share code, notes, and snippets.

@mykhailokrainik
Last active October 19, 2022 02:43
Show Gist options
  • Save mykhailokrainik/4f0322bee7c2d3c05200661fbbff8316 to your computer and use it in GitHub Desktop.
Save mykhailokrainik/4f0322bee7c2d3c05200661fbbff8316 to your computer and use it in GitHub Desktop.
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