问题:
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 = "Hello World", return 5.
代码: int lengthOfLastWord(char* s) { int count = 0; int length = strlen(s); int a = 0,b = length-1; while(s[b]==' ') //找到最后一个词的位置 b--; while(b>=a) { if(s[b] != ' ') //如果没有到最后,就让计数变量count一个字母一个字母的加 count++; else break;//到了最后跳出 b--; } return count;//最后count就是最后一个词的长度 } 解析: 这道题其实是给出一个字符窜s,要算出最后一个词的长度,那么我们只需要先利用strlen函数先计算出s的长度,然后定义b=length-1 利用s[b]额来找到最后一个词的 位置,即最后一个空格所在的位置。然后利用好while(b>=0)来让count一个子一个子的相加直到找到最后 s[b] == “”时,跳出,返回计数变量count就是最后一个词的长度。