Isogram
1. Readme
等值线
确定是否一词,或短语是等值线(isograms
).
在等值线(又称为”无定形的 Word 是一个字或短语”)没有重复字母的单词或短语的逻辑术语,但允许连字符和空格出现多次。
等值线的例子:
- lumberjacks
- background
- downstream
- six-year-old
检测 isograms 单词,但它不是等值线,因为s
重复了.
资源
维基百科https://en.wikipedia.org/wiki/Isogram
2. 开始你的表演
pub fn check(candidate: &str) -> bool { unimplemented!("Is {} an isogram?", candidate); }
3. 测试代码查看
# #![allow(unused_variables)] #fn main() { #[test] fn empty_string() { assert_eq!(check(""), true, "An empty string should be an isogram.") } #[test] //#[ignore] fn only_lower_case_characters() { assert_eq!(check("isogram"), true, "\"isogram\" should be an isogram.") } #[test] //#[ignore] fn one_duplicated_character() { assert_eq!( check("eleven"), false, "\"eleven\" has more than one \'e\', therefore it is no isogram." ) } #[test] //#[ignore] fn longest_reported_english_isogram() { assert_eq!( check("subdermatoglyphic"), true, "\"subdermatoglyphic\" should be an isogram." ) } #[test] //#[ignore] fn one_duplicated_character_mixed_case() { assert_eq!( check("Alphabet"), false, "\"Alphabet\" has more than one \'a\', therefore it is no isogram." ) } #[test] //#[ignore] fn hypothetical_isogramic_word_with_hyphen() { assert_eq!( check("thumbscrew-japingly"), true, "\"thumbscrew-japingly\" should be an isogram." ) } #[test] //#[ignore] fn isogram_with_duplicated_hyphen() { assert_eq!( check("six-year-old"), true, "\"six-year-old\" should be an isogram." ) } #[test] //#[ignore] fn made_up_name_that_is_an_isogram() { assert_eq!( check("Emily Jung Schwartzkopf"), true, "\"Emily Jung Schwartzkopf\" should be an isogram." ) } #[test] //#[ignore] fn duplicated_character_in_the_middle() { assert_eq!( check("accentor"), false, "\"accentor\" has more than one \'c\', therefore it is no isogram." ) } #}
4. 答案
# #![allow(unused_variables)] #fn main() { pub fn check(word: &str) -> bool { // Filter all non-Alphabetic character out and collect them in a new String let normalized_string: String = word.to_lowercase() .chars() .filter(|c| c.is_alphabetic()) .collect(); /* Find the char element from back and front and compare the index. If it is the same unique char the index will be the same.*/ let is_unique = |x: char, word: &str| word.find(x).unwrap() == word.rfind(x).unwrap(); // Length should be the same if it is a isogram normalized_string.len() == normalized_string .chars() .filter(|&x| is_unique(x, normalized_string.as_str())) .count() } #}