设为首页 加入收藏

TOP

[LeeCode]Length of Last Word
2015-07-20 17:17:24 来源: 作者: 【 】 浏览:4
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(二分查找)

评论

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

·Redis压力测试实战 - (2025-12-27 09:20:24)
·高并发一上来,微服 (2025-12-27 09:20:21)
·Redis 高可用架构深 (2025-12-27 09:20:18)
·Linux 系统监控 的完 (2025-12-27 08:52:29)
·一口气总结,25 个 L (2025-12-27 08:52:27)