DEV Community

DR
DR

Posted on

#58: Length of Last Word

Welcome back, LeetCoders! Today I'll be tackling problem #58, which is called Length of Last Word. From the description:

Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.

Now, there's a clean way and a not so clean way to accomplish the task we're given. Being the person I am, I'm going to go the easy route.

My thoughts on solving this problem were to simply strip the whitespace off the ends of the string, then to split it into an array and grab the length of the last word. A bigger challenge would be to deal with all of the spaces in an efficient manner so we're only left with the words in the array and not random spaces - but I'm solving it the quick and dirty way, which is to only strip what we need.

So let's get started. We're given a string s, so we'll start by just having the function return the string (makes it easier to debug).

var findLengthOfLastWord = function(s) {
   return s;
}
Enter fullscreen mode Exit fullscreen mode

Now, let's incorporate some of the logic we talked about. We need to 1) strip both ends of the string, 2) split it into an array, 3) grab the last element of the array, and 4) return that element's length. Fortunately, there's a one-liner that does the job.

return s.trim().split(' ').slice(-1)[0].length;
Enter fullscreen mode Exit fullscreen mode

You could also use trimEnd() instead of trim(), because if you think about it, the only trimming we need to do is from the end so we know what the true last word is. Both are about the same speed though, so I'll leave it with trim().

So there you have it. A truly janky solution to a classic LeetCode problem.

var lengthOfLastWord = function(s) {
   return s.trim().split(' ').slice(-1)[0].length;
};
Enter fullscreen mode Exit fullscreen mode

As always, code can be found in the Github repository.
Happy coding!

Top comments (0)