美文网首页
Lintcode422 Length of Last Word

Lintcode422 Length of Last Word

作者: 程风破浪会有时 | 来源:发表于2018-02-17 09:42 被阅读0次

    【题目描述】

    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/

    相关文章

      网友评论

          本文标题:Lintcode422 Length of Last Word

          本文链接:https://www.haomeiwen.com/subject/kmqkwxtx.html