您的位置:首页 > 其它

LeetCode:Length of Last Word

2014-05-11 19:19 357 查看
题目链接

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
.

借助strlen函数,相当于遍历两遍字符串 本文地址

class Solution {
public:
int lengthOfLastWord(const char *s) {
if(s == NULL)return 0;
int len = strlen(s), i, res = 0;
for(i = len-1; i >= 0 && s[i] == ' '; i--);//从尾部开始找到第一个非空格字符
for(; i >= 0 && s[i] != ' '; i--)res++;
return res;
}
};


遍历一遍字符串

class Solution {
public:
int lengthOfLastWord(const char *s) {
if(s == NULL)return 0;
int res = 0, cnt = 0;
for(; *s != '\0'; s++)
{
if(*s == ' ')
{
if(cnt != 0)
res = cnt;
cnt = 0;
}
else cnt++;
}
return cnt == 0 ? res : cnt;
}
};


【版权声明】转载请注明出处:/article/4879741.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: