Description#
Given a string s consisting of only letters and spaces ' ', return the length of the last word.
If the last word does not exist, return 0.
Note: A word is defined as a sequence of non-space characters.
Example:
Input: "Hello World"
Output: 5
Approach#
- Return 0 for an empty string
- Search for the last non-space character in reverse order, return 0 if not found
- Count from the non-space character until a space is encountered or the search ends, return the count
int lengthOfLastWord(char * s){
int length = strlen(s) - 1, word_length = 0;
if(length < 0)//empty string
return 0;
while (s[length] == ' ')//find the last non-space character
if(--length < 0)//check if search is complete
return 0;
for(;length >= 0 && s[length] != ' '; length--)//character is non-space and search is not complete
word_length++;
return word_length;
}
Note#
- When searching for the last non-space character, it is important to check for a space first, then decrement the length, and finally check if the search is complete to avoid out-of-bounds issues