Created
May 27, 2015 02:21
-
-
Save ferristseng/8bc0e96d50d37a132ddc to your computer and use it in GitHub Desktop.
Palindrome practice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #![feature(str_char)] | |
| use std::ascii::AsciiExt; | |
| use std::usize::MAX; | |
| fn is_palindrome(s: &str) -> bool { | |
| assert!(s.is_ascii()); | |
| let mid = s.len() / 2; | |
| let mut left_ptr = if s.len() % 2 == 0 { mid - 1 } else { mid }; | |
| let mut right_ptr = if s.len() % 2 == 0 { mid } else { mid }; | |
| while right_ptr < s.len() { | |
| if s.char_at(left_ptr) != s.char_at(right_ptr) { | |
| return false; | |
| } | |
| if left_ptr > 0 { left_ptr -= 1; } | |
| right_ptr += 1; | |
| } | |
| return true; | |
| } | |
| fn min_splits(s: &str) -> usize { | |
| assert!(s.is_ascii()); | |
| let mut min = MAX; | |
| if s.len() > 1 { | |
| for i in 1..s.len() + 1 { | |
| if is_palindrome(&s[0..i]) { | |
| let recurse = min_splits(&s[i..]); | |
| if recurse < min { | |
| min = if s[i..].len() == 0 { recurse } else { recurse + 1 }; | |
| } | |
| } | |
| } | |
| min | |
| } else { | |
| 0 | |
| } | |
| } | |
| fn main() { | |
| assert!(is_palindrome("aba")); | |
| assert!(!is_palindrome("aaba")); | |
| assert!(!is_palindrome("ab")); | |
| assert!(is_palindrome("aaabaaa")); | |
| assert!(is_palindrome("aa")); | |
| assert_eq!(min_splits("aba"), 0); | |
| assert_eq!(min_splits("aabaaaab"), 1); | |
| assert_eq!(min_splits("aaba"), 1); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment