Skip to content

Commit 52f6ba4

Browse files
committed
Add longest_palindrome
1 parent 02c20ee commit 52f6ba4

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// 5. Longest Palindromic Substring, Medium
2+
// https://leetcode.com/problems/longest-palindromic-substring/
3+
impl Solution {
4+
pub fn longest_palindrome(s: String) -> String {
5+
let n = s.len();
6+
if n <= 1 {
7+
return s;
8+
}
9+
10+
let chars = s.chars().collect::<Vec<char>>();
11+
12+
let mut ans = chars[0].to_string();
13+
let mut dp = vec![vec![false; n]; n];
14+
for i in 0..n {
15+
dp[i][i] = true;
16+
}
17+
18+
let mut max_len = 0;
19+
for end in 1..n {
20+
for start in 0..end {
21+
if chars[start] == chars[end] {
22+
if end - start == 1 || dp[start + 1][end - 1] {
23+
dp[start][end] = true;
24+
if max_len < end - start + 1 {
25+
max_len = end - start + 1;
26+
ans = chars[start..=end].iter().collect::<String>();
27+
}
28+
}
29+
}
30+
}
31+
}
32+
33+
return ans;
34+
}
35+
}
36+
37+
struct Solution {}
38+
39+
#[cfg(test)]
40+
mod tests {
41+
use super::*;
42+
use crate::{vec_string, vec_vec_i32, vec_vec_string};
43+
44+
#[test]
45+
fn test_longest_palindrome() {
46+
assert_eq!(Solution::longest_palindrome("babad".to_string()), "bab".to_string());
47+
}
48+
49+
#[test]
50+
fn test_longest_palindrome2() {
51+
assert_eq!(Solution::longest_palindrome("cbbd".to_string()), "bb".to_string());
52+
}
53+
54+
#[test]
55+
fn test_longest_palindrome3() {
56+
assert_eq!(Solution::longest_palindrome("a".to_string()), "a".to_string());
57+
}
58+
59+
#[test]
60+
fn test_longest_palindrome4() {
61+
assert_eq!(Solution::longest_palindrome("ac".to_string()), "a".to_string());
62+
}
63+
}
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
mod group_anagrams;
22
mod increasing_triplet;
33
mod length_of_longest_substring;
4-
mod set_zeroes;
4+
mod longest_palindrome;
5+
mod set_zeroes;

0 commit comments

Comments
 (0)