Leetcode 58 – Length of Last Word | Javascript
Today we will be discussing Leetcode problem 58 – Length of Last Word, and how to solve it using Javascript.
Problem Description
The problem statement is as follows:
Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Solution in Javascript
Here is the solution to the problem using Javascript:
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
s = s.trim(); // Remove leading and trailing spaces
let length = 0;
for(let i = s.length-1; i>=0; i--){
if(s[i] === ' '){
return length;
}
length++;
}
return length;
};
Explanation
We start by removing any leading and trailing spaces from the input string using the trim()
function. Then we iterate through the string from the end, counting the length of the last word until we encounter a space. We then return the length of the last word.
Conclusion
In this article, we discussed how to solve Leetcode problem 58 – Length of Last Word using Javascript. We hope you found this article helpful and will be able to use the solution provided in your coding practice.
keep up your good work.
Hhhh bro i waited for you until this late time