LeetCode Problem - Link


Problem

Given a string s consisting of words and spaces, return the length of the last word in the string.

word is a maximal 

substring

consisting of non-space characters only. 

Example 1:

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.


Sequential Approach

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function (s) {
    let words = [];


    let str = "";
    for (var i = 0; i < s.length; i++) {
        if (s[i] == " ") {
            // if empty string character
            if (str.length > 0) {
                // add the accumualted string to the array and empty the string
                words.push(str)
                str = ""
            }
        }
        else {
            // routine appending of the string char if no space is encountered
            str += s[i]
        }
    }
    if (str.length > 0) {
        // finally if a string has been accumulated, add it to our array
        words.push(str)
    }


    // return the length of the last array element
    return words[words.length - 1].length


};