01.04.2024
58. Length of Last Word easy
blog post
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), wherew
is a last word length, andb
suffix blank space lengthSpace 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
}