Question Five - 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.

If the last word does not exist, return 0.

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

Example

Given

Given s = "Hello World",
return 5.

Solution

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

Discussion

In a previous question we took a look at the trim() method of strings as well as the split() method. As you work with strings in JavaScript you will most likely find these two methods popping up quite often as well as a few others. In this question we'll need to implement these to methods again.

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

We must remove all the white space from the start and end of the string then use the split method. Here we pass a blank space to the split method which gives us an array of the words separated by spaces in the string. For example, if we passed the string 'Hello World'. After trimming and splitting we'd have ['Hello', 'World'].

Once we have this array, all we need to do is check the last value in the array and return its length. We also need to meet the condition specified by the question - If the last word does not exist, return 0.

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

results matching ""

    No results matching ""