125. Valid Palindrome in Rust
Given a string, return true when it reads the same forward and backward after ignoring non-alphanumeric characters and letter casing.
Move inward from both ends
Use two indices. Skip characters that are not letters or numbers, compare the remaining characters, and move both indices toward the centre.
fn is_palindrome(input: &str) -> bool {
let chars: Vec<char> = input
.chars()
.filter(|character| character.is_alphanumeric())
.flat_map(char::to_lowercase)
.collect();
let mut left = 0;
let mut right = chars.len().saturating_sub(1);
while left < right {
if chars[left] != chars[right] {
return false;
}
left += 1;
right -= 1;
}
true
}The algorithm takes O(n) time and uses O(n) additional space for the normalized characters.
