leet-code/longest-palindromic-substring/sol.rs

38 lines
1.3 KiB
Rust
Raw Normal View History

2022-06-19 21:57:33 +00:00
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()
}
}