58. 最後一個單詞的長度
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);
}
}