您的位置:首页 > 其它

LeetCode(59)Length of Last Word

2015-08-15 21:08 519 查看

题目

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.

分析

题目要求得出所给字符串最后一个单词的长度。

这其实是一个很简单的题目,主要有几个需要注意的点:

空字符串,自然是返回0

只有一个单词的字符串,返回长度即可

若是输入字符串为“hello “也就是说,最后是多个空字符时,返回的长度要求是最后非空字符组成的最后一个单词而不是0;

AC代码

class Solution {
public:
int lengthOfLastWord(string s) {
int len = strlen(s.c_str());

//如果是空字符串或者是单字符,则直接返回长度
if (len == 0)
return len;

int i = len-1 , j = 0;
//从后向前找到非空字符
while (i>=0 && s[i] == ' ')
--i;

for (j = i; j>=0 && s[j] != ' '; --j)
;

return i - j;
}
};


GitHub测试程序源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: