
// "Hello World" 5
// " fly me to the moon " 4
// "luffy is still joyboy" 6
// 反转遍历
pub fn length_of_last_word(s: String) -> i32 {
let mut length = 0;// 单词长度
let mut in_word = false;// 是否在单词中
for c in s.chars().rev() {// 倒序遍历
if c == ' ' {// 遇到空格
if in_word { // 如果是单词中的空格
break;
}
} else {// 先遇到非空格 把单词长度加1 in_word改为true
in_word = true;
length += 1;
}
}
length// 返回单词长度
}
// rust内置方法
pub fn length_of_last_word2(s: String) -> i32 {
s.split_whitespace()// 空格分割 返回迭代器
.last() // 取迭代器中的最后一个元素
.map_or(0, |word| word.len() as i32)// 第一个参数是默认值在last()获取不到值为None 第二参数是闭包
}
fn main() {
assert_eq!(length_of_last_word("Hello World".to_string()), 5);
assert_eq!(length_of_last_word(" fly me to the moon ".to_string()), 4);
assert_eq!(length_of_last_word("luffy is still joyboy".to_string()), 6);
assert_eq!(length_of_last_word2("Hello World".to_string()), 5);
assert_eq!(length_of_last_word2(" fly me to the moon ".to_string()), 4);
assert_eq!(length_of_last_word2("luffy is still joyboy".to_string()), 6);
}
833

被折叠的 条评论
为什么被折叠?



