Skip to content

Commit 67e9f38

Browse files
committed
feat: add solution for problem 5 in rust
1 parent ef67605 commit 67e9f38

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#![allow(dead_code)]
2+
pub fn longest_palindrome(s: String) -> String {
3+
let chars: Vec<char> = s.chars().collect();
4+
let mut res = String::new();
5+
6+
for i in 0..s.len() {
7+
for &(l, r) in [(i, i), (i, i + 1)].iter() {
8+
let (mut l, mut r) = (l, r);
9+
while l <= r && r < s.len() && chars[l] == chars[r] {
10+
if r - l + 1 > res.len() {
11+
res = s[l..=r].to_string();
12+
}
13+
if l == 0 {
14+
break;
15+
}
16+
l -= 1;
17+
r += 1;
18+
}
19+
}
20+
}
21+
22+
res
23+
}
24+
25+
#[test]
26+
fn test_longest_palindrome() {
27+
assert_eq!(longest_palindrome("babad".to_string()), "bab".to_string());
28+
assert_eq!(longest_palindrome("cbbd".to_string()), "bb".to_string());
29+
assert_eq!(longest_palindrome("a".to_string()), "a".to_string());
30+
assert_eq!(longest_palindrome("ac".to_string()), "a".to_string());
31+
}

0 commit comments

Comments
 (0)