LeetCode Entry

58. Length of Last Word

01.04.2024 easy 2024 kotlin rust

Last word length

58. Length of Last Word easy blog post substack youtube 2024-04-01_08-06.webp

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 w is a last word length, and b suffix 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
  }