Description
Length of Last Word - LeetCode
Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring1 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.
Constraints
sconsists of only English letters and spaces' '.- There will be at least one word in
s.
Code
class Solution {
public:
int lengthOfLastWord(string s) {
int end = s.length() - 1;
while(end >= 0 && s[end] == ' '){
end--;
}
int start = end;
while(start >= 0 && s[start] != ' '){
start--;
}
return end - start;
}
};Approach
IMPORTANT
Need to watchout for Trailing Whitespaces
- Create the
endpointer to point at the last character in the string - Traverse the pointer backward until the
endpointer is pointing to a non-whitespace - Create the
startpointer to point at the last character of the last word (whereendpointer is pointing at) - Traverse the
startpointer until pointing at a whitespace or start of the string - return the
endindex -startindex
Footnotes
-
A substring is a contiguous non-empty sequence of characters within a string. ↩