Topic description
Given A string s consists of Upper/lower-case alphabets and empty space characters ' ", return the length of last word in t He string.
If The last word does isn't exist, return 0.
Note:a word is defined as A character sequence consists to non-space only.
For example,
Given s = "Hello World",
Return5.
Thought: First find the string length, and then from the right to the left to traverse the string, the traversal, first skip the rightmost space, and then start to calculate the length of the last word.
Code:
Class Solution {public
:
int lengthoflastword (const char *s) {
if (s = = NULL) return
0;
int num=0;
while (S[num]!= ' ") {//Compute string length
++num;
}
if (num = = 0)//If the string is empty, that is, s= "", returns 0. return
0;
else{
int i = num-1;
while (i>=0 && s[i] = = ")//s=" a ", skips the space at the end of the string.
I.;
int len=0;
while (i>=0 && s[i]!= ') {//start traversing the length of the last word
++len;
I.
}
return len;
}
}
;