38 lines
1.3 KiB
Rust
38 lines
1.3 KiB
Rust
impl Solution {
|
|
pub fn longest_palindrome(s: String) -> String {
|
|
let mut max = "";
|
|
let bytes = s.as_bytes();
|
|
for idx in 0..s.len() {
|
|
let (mut l, mut r, mut odd, mut even) = (idx, idx, true, true);
|
|
while odd || even {
|
|
if odd {
|
|
if r == s.len() || bytes[l] != bytes[r] {
|
|
odd = false;
|
|
if r - l - 1 > max.len() {
|
|
max = s.get(l + 1..r).unwrap();
|
|
}
|
|
}
|
|
}
|
|
if even {
|
|
if r == s.len() - 1 || bytes[l] != bytes[r + 1] {
|
|
even = false;
|
|
if r - l > max.len() {
|
|
max = s.get(l + 1..r + 1).unwrap();
|
|
}
|
|
}
|
|
}
|
|
if l == 0 {
|
|
if even && r - l + 2 > max.len() {
|
|
max = s.get(l..r + 2).unwrap();
|
|
} else if odd && r - l + 1 > max.len() {
|
|
max = s.get(l..r + 1).unwrap();
|
|
}
|
|
break;
|
|
}
|
|
l -= 1;
|
|
r += 1;
|
|
}
|
|
}
|
|
max.to_string()
|
|
}
|
|
} |