设为首页 加入收藏

TOP

[LeeCode]Length of Last Word
2015-07-20 17:17:24 来源: 作者: 【 】 浏览:3
Tags:LeeCode Length Last Word

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.

求一字符串中最后一个单词中的长度,很简单,只要注意不要访问越界就哦啦~贴代码:

class Solution {
public:
    int lengthOfLastWord(const char *s) {
        int len = strlen(s);
        if (!len)
            return 0;
        int i = len - 1;
        while (i>=0&&s[i] == ' '){
            i--;
        }
        int count = 0;
        while (i>=0&&s[i] != ' '){
            count++;
            i--;
        }
        return count;
    }
};
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU 3294 Girls' research (M.. 下一篇Find Peak Element(二分查找)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·如何从内核协议栈到 (2025-12-27 03:19:09)
·什么是网络协议?有哪 (2025-12-27 03:19:06)
·TCP/ IP协议有哪些 (2025-12-27 03:19:03)
·怎样用 Python 写一 (2025-12-27 02:49:19)
·如何学习python数据 (2025-12-27 02:49:16)