23. Length of Last Word
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:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
Input: s = "luffy is still joyboy"
Output: 6Problem Breakdown:
- Trim trailing spaces from the string so we can find the last word easily.
s = s.rstrip()- Start from the end of the trimmed string and count characters until we hit a space or the beginning.
length = 0 for i in range(len(s) - 1, -1, -1): if s[i] == ' ': break length += 1- Return the count, which is the length of the last word.
return length
Summary:
Strip trailing spaces, then count characters backwards from the end until hitting a space. Alternatively, use built-in split to get the last word directly.
Time and Space Complexity:
Time Complexity: O(n) - we may traverse the entire string.
Space Complexity: O(1) - only a counter variable used (or O(n) if using split).
Python Solution:
def lengthOfLastWord(s):
s = s.rstrip()
length = 0
for i in range(len(s) - 1, -1, -1):
if s[i] == ' ':
break
length += 1
return lengthJavaScript Solution:
var lengthOfLastWord = function(s) {
s = s.trimEnd();
let length = 0;
for (let i = s.length - 1; i >= 0; i--) {
if (s[i] === ' ') break;
length++;
}
return length;
};Java Solution:
class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
int length = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') break;
length++;
}
return length;
}
}