Skip to main content

LeetCode 58 - Length of Last Word

  • Difficulty: Easy.
  • Related Topics: String.
  • Link: leetcode

Problem

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:

Input: "Hello World"
Output: 5

Solution

/**
* @param {string} s
* @return {number}
*/

var lengthOfLastWord = function (s) {
if (s.length === 1) return 1;

const words = s.trim().split(" ");
const lastWordIndex = words.length - 1;
return words.length > 0 ? words[lastWordIndex].length : 0;
};

Complexity:

  • Time complexity : O(n).
  • Space complexity : O(n).

First thought (2023.09.07)

var lengthOfLastWord = function (s) {
if (s.length === 1) return 1;

let count = 0;

for (let i = s.length - 1; i >= 0; i--) {
if (s[i] !== " ") {
count++;
}

if (count && s[i] === " ") {
return count;
}
}
return count;
};