第五周:58. Length of Last Word

来源:互联网 发布:iwatch软件 编辑:程序博客网 时间:2024/06/11 07:57

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.

解题思路:从后面往前遍历,定义res记录字符的个数,如果是字符,res自增,遇到空格就跳出循环,返回res就为最后一个单词的长度,注意一点就是当最后一个字符为空格时,不应把它当做一个英文单词。

代码:

int lengthOfLastWord(char* s) {    int slen=strlen(s);int res=0;while(s[slen-1]==' ')slen--;for(int i=slen-1;i>=0;i--){if(s[i]==' ')break;res++;}return res;}

0 0
原创粉丝点击