forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
5-Longest-Palindromic-Substring.rs
38 lines (32 loc) · 1.03 KB
/
5-Longest-Palindromic-Substring.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
impl Solution {
pub fn longest_palindrome(s: String) -> String {
let s = s.chars().collect::<Vec<char>>();
let (mut left, mut right, length): (i32, i32, i32) = (0, 0, s.len() as i32);
if length == 1 {
return s[0].to_string();
}
for i in 0..length {
// odd length
let (mut l, mut r) = (i, i);
while l >= 0 && r < length && s[l as usize] == s[r as usize] {
if r - l > right - left {
left = l;
right = r;
}
l -= 1;
r += 1;
}
// even length
let (mut l, mut r) = (i, i + 1);
while l >= 0 && r < length && s[l as usize] == s[r as usize] {
if r - l > right - left {
left = l;
right = r;
}
l -= 1;
r += 1;
}
}
s[left as usize..=right as usize].iter().collect::<String>()
}
}