LeetCode Entry
58. Length of Last Word
Last word length
58. Length of Last Word easy
blog post
substack
youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/557
Problem TLDR
Last word length #easy
Intuition
There are many ways, let’s try to write an efficient solution. Iterate from the end, stop after the first word.
Approach
In Kotlin we can use first, takeWhile and count.
In Rust let’s to write a simple for loop over bytes.
Complexity
-
Time complexity: \(O(w + b)\), where
wis a last word length, andbsuffix blank space length -
Space complexity: \(O(1)\)
Code
fun lengthOfLastWord(s: String) =
((s.lastIndex downTo 0).first { s[it] > ' ' } downTo 0)
.asSequence().takeWhile { s[it] > ' ' }.count()
pub fn length_of_last_word(s: String) -> i32 {
let mut c = 0;
for b in s.bytes().rev() {
if b > b' ' { c += 1 } else if c > 0 { return c }
}
c
}