leetcode简单题11 N.58 最后一个单词长度 rust描述


 

// "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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值