58. Length of Last Word

Length of Last Word

Length of Last Word


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.


Example 2:

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.


Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

Approach) Without Split

var lengthOfLastWord = function(s) {
     
    let index = s.length - 1;
    let output = 0;

    while (s[index] === ' ' && index >= 0) index -= 1;

    while (s[index] !== ' ' && index >= 0) {

        output += 1;
        index -= 1;

    }
    return output;
};

Approach) One Liner

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
     return s.trim().split(' ').pop().length;
};

Approach) Inbuilt Function

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
   return s
        .split(' ')
        .filter(char => char)
        .pop()
        .length;
};

Approach) Regex

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    let m = s.trim().match(/(\w)+$/)
    return m ? m[0].length : 0;
};


Conclusion

That’s all folks! In this post, we solved LeetCode problem 58. Length of Last Word

I hope you have enjoyed this post. Feel free to share your thoughts on this.

You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.


In this blog, I have tried to collect & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!

Comments

Popular Post