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
Runtime: 52 ms, faster than 81.86% of JavaScript online submissions for Length of Last Word.
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
const words = s.trim().split(' ');
return words[words.length - 1].length;
};
Runtime: 52 ms, faster than 81.86% of JavaScript online submissions for Length of Last Word.
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
const words = s.match(/\w+/g);
return words ? words[words.length - 1].length : 0;
};
Runtime: 48 ms, faster than 100.00% of JavaScript online submissions for Length of Last Word.
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
if (s.length < 1) {
return 0;
}
let count = 0;
for (let i = s.length - 1; i >= 0; i--) {
if (s[i] === ' ') {
if (count < 1) {
continue;
} else {
return count;
}
}
count++;
}
return count;
};