Skip to content

Commit

Permalink
impl solution longest_palindromic_substring
Browse files Browse the repository at this point in the history
  • Loading branch information
SKTT1Ryze committed Oct 15, 2023
1 parent 88615fb commit 3f07b23
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
2 changes: 1 addition & 1 deletion leetcode/src/problems/longest_palindromic_substring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ impl Problem for LongestPalindromicSubstring {
r#"Given a string s, return the longest palindromic substring in s."#.into()
}
fn labels(&self) -> Vec<String> {
["String".into()].into()
["String".into(), "DP".into()].into()
}
}
38 changes: 37 additions & 1 deletion leetcode/src/solutions/longest_palindromic_substring.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::Solution;
use std::collections::HashMap;

pub struct LongestPalindromicSubstring;

Expand Down Expand Up @@ -32,6 +33,41 @@ impl Solution for LongestPalindromicSubstring {

impl LongestPalindromicSubstring {
pub fn longest_palindrome(s: String) -> String {
todo!()
let mut max = "";
let mut map: HashMap<char, Vec<_>> = HashMap::new();

for (end, ch) in s.chars().enumerate() {
map.entry(ch).or_default().push(end);

for &start in map.get(&ch).unwrap_or(&vec![]) {
let subs = &s[start..end + 1];

if Self::check_palindromic(subs) {
if subs.len() > max.len() {
max = subs;
}
break;
}
}
}

max.into()
}

fn check_palindromic(s: &str) -> bool {
let chars: Vec<_> = s.chars().collect();
let len = chars.len();
let mut p1 = 0;
let mut p2 = len - 1;

while p1 < p2 {
if chars[p1] != chars[p2] {
return false;
}
p1 += 1;
p2 -= 1;
}

true
}
}

0 comments on commit 3f07b23

Please sign in to comment.