Skip to content

Commit

Permalink
LeetCode's Length of Last Word Challenge
Browse files Browse the repository at this point in the history
Given a string s consisting of words and spaces,
return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
  • Loading branch information
Tunzeki committed Jun 15, 2023
1 parent a42fe33 commit 6fac150
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions javascript/lengthOfLastWord.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Visit https://leetcode.com/problems/length-of-last-word/description/
* for full problem description
*
* Given a string s consisting of words and spaces,
* return the length of the last word in the string.
* A word is a maximal substring consisting of non-space characters only.
*
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function (s) {
// Remove white spaces at both ends of the string
// This ensures that the string ends with a word
const sTrimmed = s.trim();
// Put substrings separated by one whitespace ' ' into an array
const sArray = sTrimmed.split(' ');
// Return the length of the last element in the array
return sArray[sArray.length - 1].length;

};

0 comments on commit 6fac150

Please sign in to comment.