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.
For example:
s result
"Hello World" 5
"a " 1
" a " 1
" ba " 2
"ba " 2
The following is my code:
int lengthOfLastWord(const char* s)
{
const char* end=s;
while (*end != '\0')
{
++end;
}
--end;
while ((end >= s) && (*end == ' '))
{
--end;
}
const char* start = end;
while ((start >= s) && (*start != ' '))
{
--start;
}
return end-start;
}
"b a " 2
\$\endgroup\$"ba " 2
\$\endgroup\$