Browse Source

feat: valid_palidrome

Zhang Li 1 year ago
parent
commit
6c884463ee
2 changed files with 29 additions and 0 deletions
  1. 1 0
      src/solutions/str/mod.rs
  2. 28 0
      src/solutions/str/valid_palindrome.rs

+ 1 - 0
src/solutions/str/mod.rs

@@ -2,3 +2,4 @@ mod multiply_strings;
 mod strstr;
 mod minimum_window_substring;
 mod string_to_integer;
+mod valid_palindrome;

+ 28 - 0
src/solutions/str/valid_palindrome.rs

@@ -0,0 +1,28 @@
+struct Solution;
+
+impl Solution {
+    pub fn is_palindrome(s: String) -> bool {
+        let forward    = s.chars()
+            .filter (|c| c.is_alphanumeric())
+            .map(|c| c.to_lowercase().to_string());
+
+        let backward   = s.chars()
+            .rev()
+            .filter (|c| c.is_alphanumeric())
+            .map(|c| c.to_lowercase().to_string());
+
+        forward.partial_cmp(backward)==Some(std::cmp::Ordering::Equal)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_ispalindrome() {
+        let s = String::from("A man, a plan, a canal: Panama");
+        let res = Solution::is_palindrome(s);
+        assert_eq!(res, true);
+    }
+}