LeetCode Continued: Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters' ', return the length of last word in the string.

Note: A word is defined as a character sequence consists of non-space characters only.

The problem specifies that a word is defined as a character sequence, but does not consist of spaces. So the fist thing we want to do is trim the front and back of the entire string, and get rid of all spaces. Next, we’ll split the string at the spaces in between the words so we can have a new array of words separated by commas. So for example, if we split the string [‘Merry Christmas’], it would look like [‘Merry’, ‘Christmas’].

var lengthOfLastWord = function(s) {
var sArr = s.trim().split(' ');

Now that we have this new array, all we need to do now is check the last word in the array and return the length. Don’t forget, we also need to meet the condition, that if the last word doesn’t exist, we should return 0.

var lengthOfLastWord = function(s) {
var sArr = s.trim().split(' ');
if(sArr.length === 0){
return 0;
}else{
return sArr[sArr.length - 1].length;
}
};

We took advantage of three valuable JavaScript methods that really make our lives easier: trim, split, and length. These methods are very popular and are used in many LeetCode solutions. Happy Coding! :D

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store