From 7d65224d607742b9fbb6d834a426a296f41bbabc Mon Sep 17 00:00:00 2001 From: m4siri Date: Mon, 1 Dec 2025 22:07:59 +0545 Subject: solve: 05_longest-palindromic-substring god i fucking hate this. lots of hit & trial on this one specially. instant fixing right after failing a test without thinking aot. --- 05_longest-palindromic-substring/src/main.rs | 64 +++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) (limited to '05_longest-palindromic-substring/src/main.rs') diff --git a/05_longest-palindromic-substring/src/main.rs b/05_longest-palindromic-substring/src/main.rs index e7a11a9..01300ef 100644 --- a/05_longest-palindromic-substring/src/main.rs +++ b/05_longest-palindromic-substring/src/main.rs @@ -1,3 +1,65 @@ fn main() { - println!("Hello, world!"); + let s = "abcda".to_string(); + dbg!(Solution::longest_palindrome(s)); +} + +struct Solution(()); + +impl Solution { + pub fn longest_palindrome(s: String) -> String { + use std::collections::HashMap; + + if s.len() == 1 { + return s; + } + let s = s.chars().collect::>(); + if s.len() == 2 { + if s[0] != s[1] { + return s[0].to_string(); + } else { + return s.into_iter().collect::(); + } + } + + let mut hm: HashMap> = HashMap::new(); + let mut ls = s[0].to_string(); + + for (idx, c) in s.iter().enumerate() { + if let Some(indices) = hm.get(&c) { + + for c_idx in indices.iter() { + let ss = &s[*c_idx..=idx]; + if Self::is_palindrome(ss) && ss.len() > ls.len() { + ls = ss.clone().into_iter().collect::(); + } + } + + hm.entry(*c) + .and_modify(|v| v.push(idx)); + + } else { + hm.insert(c.clone(), vec![idx]); + } + } + + ls + } + + pub fn is_palindrome(slice: &[char]) -> bool { + if slice.len() == 2 { + return &slice[0] == &slice[1]; + } + + let mut l = 0; + let mut r = slice.len() - 1; + + while l < r { + if slice[l] != slice[r] { + return false; + } + l += 1; + r -= 1; + } + return true; + } } -- cgit v1.2.3