Leetcode--Rust--简单3

58. 最后一个单词的长度

/* 
给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词
就是最后出现的单词。如果不存在最后一个单词,请返回 0 。
说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。

示例:
输入: "Hello World"
输出: 5
*/
pub struct Solution {}
impl Solution {
    pub fn length_of_last_word(s: String) -> i32 {
        let seq: Vec<char> = s.chars().rev().collect();
        let mut result = 0;
        let mut b_started = false;
        for ch in seq {
            if ch == ' ' && b_started {
                break;
            }

            if ch != ' ' {
                b_started = true;
                result += 1;
            }
        }
        return result as i32;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_53() {
        assert_eq!(Solution::length_of_last_word("Hello World".to_owned()), 5);
        assert_eq!(Solution::length_of_last_word("       ".to_owned()), 0);
        assert_eq!(Solution::length_of_last_word("".to_owned()), 0);
        assert_eq!(Solution::length_of_last_word("     rrrrr  ".to_owned()), 5);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章