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.
For example,
Given s =
return
Given s =
"Hello World"
,return
5
.Code
int lengthOfLastWord(const char *s) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int len = strlen(s); int i = len - 1; while(i >= 0 && (s[i] == ' ' || s[i] == '\t')) --i; int j = i; while(j >= 0 && s[j] != ' ' && s[j] != '\t') --j; return (i - j); }
No comments:
Post a Comment