Skip to main content

< Back to Data Structures and Algorithms

LeetCode 58 ยท Strings

Length of Last Word

How long the last word is, once trailing spaces are trimmed and the rest split into words.

Step through it

Examples
Edge cases
s
  1. 0
  2. 1
  3. 2
  4. f3
  5. l4
  6. y5
  7. 6
  8. m7
  9. e8
  10. 9
  11. 10
  12. 11
  13. t12
  14. o13
  15. 14
  16. 15
  17. 16
  18. t17
  19. h18
  20. e19
  21. 20
  22. m21
  23. o22
  24. o23
  25. n24
  26. 25
  27. 26

Output

returns 4

โœ“ the expected answer

The code

/**
 * Determine the length of the last word in a string.
 * @param {string} s
 * @return {number}
 */
 const lengthOfLastWord = s => {   
    /* Create an array of words using:
       - .trimEnd() to remove trailing whitespace.
       - .split(' ') to create the array of words, splitting at each space in the string. */
    const words = s.trimEnd().split(' ')
    // The last word is the last entry in the words array.
    const lastWord = words[words.length-1]
    
    return lastWord.length
}

View it on GitHub (opens in a new tab)