From 51fc3a4ffbefcdf240b05d0c22a34c46a6331556 Mon Sep 17 00:00:00 2001 From: Bauke Date: Sat, 9 Apr 2022 00:32:20 +0200 Subject: [PATCH] Solve valid-palindrome. --- source/lib.rs | 1 + source/valid_palindrome/mod.rs | 14 ++++++++++++++ tests/valid_palindrome.rs | 11 +++++++++++ 3 files changed, 26 insertions(+) create mode 100644 source/valid_palindrome/mod.rs create mode 100644 tests/valid_palindrome.rs diff --git a/source/lib.rs b/source/lib.rs index d011a51..3c40e85 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -9,4 +9,5 @@ pub mod reverse_integer; pub mod roman_to_integer; pub mod two_sum; pub mod valid_anagram; +pub mod valid_palindrome; pub mod valid_parenthesis; diff --git a/source/valid_palindrome/mod.rs b/source/valid_palindrome/mod.rs new file mode 100644 index 0000000..3b534a2 --- /dev/null +++ b/source/valid_palindrome/mod.rs @@ -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::(); + let reversed = normalized.rev().collect::(); + + regular == reversed +} diff --git a/tests/valid_palindrome.rs b/tests/valid_palindrome.rs new file mode 100644 index 0000000..bb22cc2 --- /dev/null +++ b/tests/valid_palindrome.rs @@ -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); +}