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.
Examples
Example 1: Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5. Example 2: Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4. Example 3: Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" with length 6.
Python Solution
def lengthOfLastWord(s: str) -> int:
# Trim trailing spaces and split by spaces
words = s.strip().split()
return len(words[-1]) if words else 0
Java Solution
class Solution {
public int lengthOfLastWord(String s) {
int length = 0;
int i = s.length() - 1;
// Skip trailing spaces
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
// Count characters of last word
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}
return length;
}
}
C++ Solution
class Solution {
public:
int lengthOfLastWord(string s) {
int length = 0;
int i = s.length() - 1;
// Skip trailing spaces
while (i >= 0 && s[i] == ' ') {
i--;
}
// Count characters of last word
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
};
JavaScript Solution
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
// Trim trailing spaces and split by spaces
const words = s.trim().split(' ');
return words[words.length - 1].length;
};
C# Solution
public class Solution {
public int LengthOfLastWord(string s) {
int length = 0;
int i = s.Length - 1;
// Skip trailing spaces
while (i >= 0 && s[i] == ' ') {
i--;
}
// Count characters of last word
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
}
Complexity Analysis
- Time Complexity: O(n) where n is the length of the string
- Space Complexity: O(1) for iterative approach, O(n) for split approach
Solution Explanation
There are two main approaches to solve this problem:
- Split approach:
- Trim trailing spaces
- Split string by spaces
- Return length of last word
- Iterative approach:
- Start from end of string
- Skip trailing spaces
- Count characters until space or start
Key points:
- Handle trailing spaces
- Handle empty strings
- No need for extra space in iterative approach
- Simple and efficient solution