Sponsored
Sponsored
This approach involves trimming any trailing spaces from the string, splitting it into words using spaces as delimiters, and then simply returning the length of the last word in the resulting list of words.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), no extra space is used besides counters.
1function lengthOfLastWord(s) {
2 let words = s.trim().split(' ');
3 return words[words.length - 1].length;
4}
5
6console.log(lengthOfLastWord("Hello World")); // Outputs 5
The JavaScript approach trims the trailing spaces, splits the string, and then returns the length of the last word in the list.
This approach involves traversing the string from the end, skipping spaces, and then counting the length of the last word by scanning backward.
Time Complexity: O(n)
Space Complexity: O(1)
1using System;
2
class Solution {
public int LengthOfLastWord(string s) {
int length = 0, i = s.Length - 1;
while (i >= 0 && s[i] == ' ') i--;
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
static void Main(string[] args) {
Solution solution = new Solution();
Console.WriteLine(solution.LengthOfLastWord(" fly me to the moon ")); // Outputs 4
}
}
The C# solution performs similar reverse string traversal to determine the length of the last word according to the conditions given in the problem statement.