class Solution:
def lengthOfLastWord(self, s: str) -> int:
i = len(s) - 1
# Skip trailing spaces
while i >= 0 and s[i] == ' ':
i -= 1
length = 0
# Count length of last word
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return length
class Solution {
public:
int lengthOfLastWord(string s) {
int i = s.size() - 1;
// Skip trailing spaces
while (i >= 0 && s[i] == ' ') i--;
int length = 0;
// Count length of last word
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
};
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1;
// Skip trailing spaces
while (i >= 0 && s.charAt(i) == ' ') i--;
int length = 0;
// Count length of last word
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}
return length;
}
}
var lengthOfLastWord = function(s) {
let i = s.length - 1;
// Skip trailing spaces
while (i >= 0 && s[i] === ' ') i--;
let length = 0;
// Count length of last word
while (i >= 0 && s[i] !== ' ') {
length++;
i--;
}
return length;
};
Given a string s
consisting of words and spaces, return the length of the last word in the string.
A word is defined as a maximal substring consisting of non-space characters only.
s
may contain leading or trailing spaces.s
.Constraints:
s
consists of only English letters and spaces ' '
.At first glance, the problem appears simple—just find the last word and return its length. However, there are edge cases to consider, such as trailing spaces or multiple spaces between words. A brute-force approach might be to split the string by spaces and pick the last non-empty substring, but this may use extra memory and be less efficient.
To optimize, we can process the string from the end, skipping any trailing spaces, and then count the characters of the last word until we hit a space or the start of the string. This avoids extra space and is efficient.
This approach is akin to reading a sentence backwards, ignoring any empty space at the end, and then counting the letters of the first word you encounter.
This approach is chosen because:
Input: s = "Hello World "
This process ensures that even if there are extra spaces at the end, they are ignored, and only the last word is considered.
The optimized approach is preferred for large inputs due to its constant space usage and linear time.
The "Length of Last Word" problem is elegantly solved by scanning the string from the end, skipping any trailing spaces, and counting the characters of the final word. This approach is efficient, concise, and handles all edge cases without any extra memory allocation. The key insight is to avoid unnecessary splitting or extra data structures and work directly with the characters of the string.