1
Fork 0

Solve valid-palindrome.

This commit is contained in:
Bauke 2022-04-09 00:32:20 +02:00
parent ea43830954
commit 51fc3a4ffb
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
3 changed files with 26 additions and 0 deletions

View File

@ -9,4 +9,5 @@ pub mod reverse_integer;
pub mod roman_to_integer; pub mod roman_to_integer;
pub mod two_sum; pub mod two_sum;
pub mod valid_anagram; pub mod valid_anagram;
pub mod valid_palindrome;
pub mod valid_parenthesis; pub mod valid_parenthesis;

View File

@ -0,0 +1,14 @@
pub fn is_palindrome(string: String) -> bool {
let normalized = string.chars().filter_map(|c| {
if char::is_alphanumeric(c) {
Some(c.to_ascii_lowercase())
} else {
None
}
});
let regular = normalized.clone().collect::<String>();
let reversed = normalized.rev().collect::<String>();
regular == reversed
}

11
tests/valid_palindrome.rs Normal file
View File

@ -0,0 +1,11 @@
use leetcode::valid_palindrome::is_palindrome;
use test_case::test_case;
#[test_case("A man, a plan, a canal: Panama", true; "valid")]
#[test_case("race a car", false; "invalid")]
#[test_case("", true; "empty")]
#[test_case(" \t", true; "whitespace only")]
fn test_valid_palindrome(input: &str, expected: bool) {
assert_eq!(is_palindrome(input.to_string()), expected);
}