Last active
October 19, 2022 02:43
-
-
Save mykhailokrainik/4f0322bee7c2d3c05200661fbbff8316 to your computer and use it in GitHub Desktop.
Find the longest palindrome in a string. #Rust #Polindrome
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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