Skip to content

Commit 615cbc8

Browse files
committed
longest_palindrome
1 parent f71b494 commit 615cbc8

File tree

3 files changed

+45
-141
lines changed

3 files changed

+45
-141
lines changed

src/find_median_sorted_arrays.rs.bk

Lines changed: 0 additions & 141 deletions
This file was deleted.

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ pub mod two_sum;
22
pub mod add_two_numbers;
33
pub mod length_of_longest_substring;
44
pub mod find_median_sorted_arrays;
5+
pub mod longest_palindrome;

src/longest_palindrome.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Brute Force
2+
pub fn longest_palindrome(input: &str) -> &str {
3+
let length = input.len();
4+
let mut sub: &str;
5+
for i in 0..length {
6+
for j in 0..i + 1 {
7+
sub = &input[j..length - i + j];
8+
if is_palindrome(sub.to_string()) {
9+
return sub;
10+
}
11+
}
12+
}
13+
return &input[0..0];
14+
}
15+
16+
pub fn is_palindrome(s: String) -> bool {
17+
let mut rs = s.clone().into_bytes();
18+
rs.reverse();
19+
return rs == s.into_bytes();
20+
}
21+
22+
#[cfg(test)]
23+
mod test {
24+
use super::is_palindrome;
25+
use super::longest_palindrome;
26+
27+
#[test]
28+
fn test_is_palindrome() {
29+
assert_eq!(is_palindrome(String::from("aba")), true);
30+
assert_eq!(is_palindrome(String::from("ab")), false);
31+
assert_eq!(is_palindrome(String::from("a")), true);
32+
assert_eq!(is_palindrome(String::from("abab")), false);
33+
}
34+
35+
#[test]
36+
fn test_longest_palindrome() {
37+
assert_eq!(longest_palindrome("babad"), "bab");
38+
assert_eq!(longest_palindrome("abccba"), "abccba");
39+
assert_eq!(longest_palindrome("cabccbad"), "abccba");
40+
assert_eq!(longest_palindrome("xbacabccbaddab"), "abccba");
41+
assert_eq!(longest_palindrome("abccbaddxe"), "abccba");
42+
assert_eq!(longest_palindrome("ddxeabccba"), "abccba");
43+
}
44+
}

0 commit comments

Comments
 (0)