
Problem Statement
The task is to determine the length of the last word in a given string s
. The string consists of multiple words separated by spaces, where a word is defined as a sequence of non-space characters. The challenge lies in efficiently navigating through the string, identifying the boundaries of the last word, and computing its length, especially considering the string might start or end with spaces and can be up to 10,000 characters long.
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.
Constraints
1 <= s.length <= 104
s
consists of only English letters and spaces' '
.- There will be at least one word in
s
.
Approach and Intuition
To solve this problem, the primary goal is to identify the last word in the string and determine its length.
Trimming the String:
- The string may have leading or trailing spaces which need to be ignored. Using the string
strip()
method will ensure all leading and trailing spaces are removed, making it easier to accurately identify the last word.
- The string may have leading or trailing spaces which need to be ignored. Using the string
Splitting the Words:
- Once stripped of unnecessary spaces, split the string using spaces as the delimiter. This will break the string into a list of words. An example with the string
" fly me to the moon "
after stripping and splitting will result in the list["fly", "me", "to", "the", "moon"]
.
- Once stripped of unnecessary spaces, split the string using spaces as the delimiter. This will break the string into a list of words. An example with the string
Identifying the Last Word:
- The last element of the list generated from the previous step will always be the last word due to how the splitting works. Thus, selecting the last element in the list will yield the last word.
Calculating the Length:
- Using Python's
len()
function on the last word obtained gives the length directly. This operation is constant time,O(1)
, as getting the length of a string is a fundamental operation.
- Using Python's
By breaking the problem down stepwise, handling possible string anomalies (like extra spaces), and using built-in string functions, the problem becomes much more straightforward to tackle programmatically. This approach ensures that we handle various edge cases like strings with multiple spaces between words or trailing spaces effectively.
Solutions
- C++
- Java
- C
- JavaScript
- Python
class Solution {
public:
int getLastWordLength(string str) {
int length = 0;
int finalIndex = str.length() - 1;
// Remove trailing spaces
while (finalIndex >= 0 && str[finalIndex] == ' ') finalIndex--;
// Count the characters of the last word
while (finalIndex >= 0 && str[finalIndex] != ' ') {
length++;
finalIndex--;
}
return length;
}
};
The provided C++ program defines a method getLastWordLength
which calculates the length of the last word in a given string. This implementation avoids counting trailing spaces and iteratively counts the characters until it encounters a space, marking the beginning of the last word. The steps followed by the code are:
- Initialize
length
to 0, to keep track of the number of characters in the last word. - Determine
finalIndex
as the position of the last character in the string. - Strip any trailing spaces by decrementing
finalIndex
until a non-space character is found. - Count backwards from
finalIndex
, incrementinglength
with each non-space character, until a space is encountered orfinalIndex
reaches the start of the string. - Return the
length
as the size of the last word.
This method effectively handles strings with trailing spaces and returns the accurate length of the final word.
class Solution {
public int lastWordLength(String input) {
input = input.trim();
return input.length() - input.lastIndexOf(" ") - 1;
}
}
The provided Java function lastWordLength
calculates the length of the last word in a given string. This function first removes any leading and trailing spaces from the input string using the trim()
method. It then determines the length of the last word by subtracting the index of the last space from the total length of the string and adjusting by one to account for index offset. This function's approach is efficient because it avoids splitting the string into an array, focusing only on trimming and calculating based on the last space index, ensuring reduced time and space complexity especially for long strings.
int lastWordLength(char* string) {
int length = 0;
int i = strlen(string) - 1;
while (i >= 0 && string[i] == ' ') i--;
while (i >= 0 && string[i] != ' ') {
length++;
i--;
}
return length;
}
The provided C function named lastWordLength
calculates the length of the last word in a given string. This function is useful for situations where you need to determine the number of characters in the last word of a sentence or any text.
Here's a breakdown of how the function works:
- Initialize an integer
length
to 0. This variable will store the length of the last word. - Determine the position of the last character in the string that is not a space by initializing
i
to the last index of the string and decrementing it as long as the current character is a space. - Once non-space characters start (indicating the beginning of the last word), count these characters by incrementing the
length
until a space or the start of the string is encountered.
By the end of the function, length
holds the number of characters in the last word of the string and is returned as the output. This logic ensures that trailing spaces are ignored and only the last word is considered for length calculation.
var getLastWordLength = function (str) {
str = str.trim(); // trim the spaces at the end
return str.length - str.lastIndexOf(" ") - 1;
};
The problem "Length of Last Word" aims to determine the length of the last word in a given string. The provided solution uses JavaScript to achieve this. The function getLastWordLength
processes a string to find the length of its last word.
- Initialize the function
getLastWordLength
that takes a stringstr
as its parameter. - Trim any trailing spaces from the string using
str.trim()
. - Find the length of the last word by subtracting the position of the last space from the total length of the string. This is achieved using
str.length - str.lastIndexOf(" ") - 1
. - Return the calculated length.
The function efficiently calculates the length of the last word by locating the last space and considering any trimmed spaces to ensure correctness. The approach is straightforward and effective for strings where words are separated by spaces.
class Solution:
def getLastWordLength(self, input_string: str) -> int:
return 0 if not input_string or input_string.isspace() else len(input_string.split()[-1])
The provided Python solution addresses the problem of determining the length of the last word in a given string. The function getLastWordLength
in the Solution
class takes a string as input and returns an integer representing the length of the last word. Here's an outline of how the function operates:
- First, you check if the
input_string
is either empty or contains only whitespace using conditionsnot input_string
orinput_string.isspace()
. If either condition is true, the function returns0
. - If the input string has content,
input_string.split()
splits the string into words based on whitespace. - The last word in the list of words obtained from the split operation is accessed using
[-1]
, and its length is computed and returned withlen()
.
The solution effectively handles edge cases such as empty strings, strings consisting only of spaces, and strings with actual words. The use of split()
ensures that any leading, trailing, or multiple spaces within the string do not affect the determination of the last word's length, making this solution robust and efficient for the given task.
No comments yet.