FastPrepLength of the Last Word

Length of the Last Word

Bloomberg LP logoBloomberg LP● EasyNEW GRADPHONE SCREEN
Learn

Problem statement

Given a string text containing English letters and spaces, return the length of its last word.

A word is a maximal contiguous sequence of non-space characters. The input contains at least one word and may have leading, trailing, or repeated spaces.

Function

lengthOfLastWord(text: String) → int

Examples

Example 1

text = "Hello World"return = 5

The last word is World, whose length is 5.

Example 2

text = "   fly me   to   the moon  "return = 4

Trailing spaces are ignored. The last word is moon.

Example 3

text = "luffy is still joyboy"return = 6

The final word is joyboy.

Constraints

  • 1 <= text.length <= 100000
  • text contains only English letters and the space character.
  • text contains at least one word.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int lengthOfLastWord(String text) {
    // Write your code here.
}
text"Hello World"
expected5
Checking account…