DEV Community

loading...

Solving LeetCode - Length of Last Word

phariale profile image pharia-le ・1 min read

Question

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"
Output: 5
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: s = " "
Output: 0
Enter fullscreen mode Exit fullscreen mode

Constraints:

  • <= s.length <= 104
  • s consists of only English letters and spaces ' '

Let's Go!

Solve by using PREP.

  • P - One parameter. A string s
  • R - Return number that represents length of last word in s
  • E - Examples provided by question. (See Above)
  • P - See Below
var lengthOfLastWord = function(s) {
    // remove whitespace & split s by empty space ' ' 
    // return the length of the last element of the array or 0
};

Enter fullscreen mode Exit fullscreen mode

Translate into code...

var lengthOfLastWord = function(s) {
    // remove whitespace & split s by empty space ' ' 
    const words = s.trim().split(' ')
    // return the length of the last element of the array or 0
    return words.length > 0 ? words[words.length-1].length : 0
};

Enter fullscreen mode Exit fullscreen mode

Conclusion

& Remember... Happy coding, friends! =)

Sources

Discussion (0)

pic
Editor guide