Problem
Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
1 |
|
Explanation
-
We can solve it in one line. First trim the string and get its length
len
, then subtract 1 is the last index, then again subtract the last index of space of the trimmed string, which returns us the last word’s length. -
The second way is create a pointer that starts from the end, find the last character’s index, then set the result counter to 0. Increase 1 until the pointer poinits to empty space. Return the counter result.
Solution
1 |
|