~statianzo/cracking

3c99f1b720b59882a7e82a58c81c3c7a563fd583 — Jason Staten 3 years ago a91adc9
1.4
2 files changed, 58 insertions(+), 0 deletions(-)

A src/cc01_4.rs
M src/lib.rs
A src/cc01_4.rs => src/cc01_4.rs +57 -0
@@ 0,0 1,57 @@
//! # Cracking the Coding Interview 1.4
//! ## Problem
//! Palindrome Permutation: Given a string, write a function to check if it is
//! a permutation of a palindrome. A palindrome is a word or phrase that is the
//! same forwards and backwards. A permutation is a rearrangement of letters.
//! The palindrome does not need to be limited to just dictionary words.
//!
//! ```
//! # use cracking::cc01_4::is_palindromeable;
//! let input = "tact coa";
//! assert!(is_palindromeable(input))
//! ```

use std::collections::HashMap;

pub fn is_palindromeable(s: &str) -> bool {
    let mut counts = HashMap::new();
    for c in s.chars().filter(|c| c.is_alphanumeric()) {
        *counts.entry(c).or_default() += 1;
    }

    let mut has_odd = false;
    for v in counts.values() {
        if v % 2 == 1 {
            if has_odd {
                return false;
            }
            has_odd = true;
        }
    }
    true
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_empty() {
        assert!(is_palindromeable(""))
    }

    #[test]
    fn test_palindrome() {
        assert!(is_palindromeable("aba"))
    }

    #[test]
    fn test_nonpalindrome() {
        assert!(!is_palindromeable("abac"))
    }

    #[test]
    fn test_spaces() {
        assert!(is_palindromeable("tact coa"))
    }
}

M src/lib.rs => src/lib.rs +1 -0
@@ 1,6 1,7 @@
pub mod cc01_1;
pub mod cc01_2;
pub mod cc01_3;
pub mod cc01_4;
pub mod cc01_5;
pub mod cc17_1;
pub mod cc17_2;