Length of Last Word
Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5Example 2:
Input: s = " "
Output: 0Constraints:
1 <= s.length <= 104sconsists of only English letters and spaces' '.
Solutions
π Python
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.rsplit(maxsplit=1)[-1]) if len(s.strip()) else 0π§ Cpp
class Solution {
public:
int lengthOfLastWord(string s)
{
int counter = 0;
auto riter = s.rbegin();
for(; *riter == ' '; riter++);
for(; *riter!=' ' && riter!=s.rend(); riter++, counter++);
return counter;
}
};Last updated
Was this helpful?