您的位置:首页 > 其它

Lintcode422 Length of Last Word solution 题解

2018-04-10 00:00 162 查看
【题目描述】

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.

Notice

A word is defined as a character sequence consists of non-space characters only.

给定一个字符串, 包含大小写字母、空格' ',请返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

注意事项:

一个单词的界定是,由字母组成,但不包含任何的空格。

【题目链接】

www.lintcode.com/en/problem/length-of-last-word/

【题目解析】

根据题目的描述,我们可以知道最后一个单词的定义为最后一个空格之后的内容。

所以简单的,我们通过string.rfind方法,从后往前找到第一个空格,其位置为p。

则最后一个的单词的长度即为s.size() - p - 1。

有两点需要注意的地方:

s的末尾的' ',比如"hello world "。因此我们要先去掉s末尾的' '。

s不包含空格,比如"haha",此时求出的p=-1。不过刚好也满足s.size() - p - 1为正确答案。

【参考答案】

www.jiuzhang.com/solutions/length-of-last-word/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Lintcode