diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 3f28909..9772932 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -110,4 +110,5 @@ mod p42_trapping_rain_water; mod p58_length_of_last_word; mod p151_reverse_words_in_a_string; mod p28_find_the_index_of_the_first_occurrence_in_a_string; -mod p68_text_justification; \ No newline at end of file +mod p68_text_justification; +mod p125_valid_palindrome; \ No newline at end of file diff --git a/src/problem/p125_valid_palindrome.rs b/src/problem/p125_valid_palindrome.rs new file mode 100644 index 0000000..9994b55 --- /dev/null +++ b/src/problem/p125_valid_palindrome.rs @@ -0,0 +1,51 @@ +/** + * [125] Valid Palindrome + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn is_palindrome(s: String) -> bool { + let s = s.to_lowercase(); + let mut result = Vec::new(); + + for c in s.chars() { + if c.is_ascii_alphabetic() || c.is_digit(10) { + result.push(c); + } + } + + if result.len() <= 1 { + return true; + } + + let mut i = 0; + let mut j = result.len() - 1; + + while i < j { + if result[i] != result[j] { + return false; + } + + i += 1; + j -= 1; + } + + true + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_125() { + assert!(Solution::is_palindrome("A man, a plan, a canal: Panama".to_owned())); + assert!(!Solution::is_palindrome("0P".to_owned())); + } +}