设为首页 加入收藏

TOP

Leetcode 细节实现 Length of Last Word
2015-07-20 17:44:12 来源: 作者: 【 】 浏览:1
Tags:Leetcode 细节 实现 Length Last Word

Length of Last Word

Total Accepted: 17518 Total Submissions: 59526My Submissions

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.

题意:返回一个句子的最后一个单词的长度

思路:将字符串分割成单词,然后返回最后一个的长度即可

python代码

class Solution:
    # @param s, a string
    # @return an integer
    def lengthOfLastWord(self, s):
        s_split = s.split()
        return 0 if len(s_split) == 0 else len(s_split[-1])

c++代码

int lengthOfLastWord(const char *s){
	const string str(s);
	auto a = find_if(str.rbegin(), str.rend(), ::isalpha);
	auto b = find_if_not(a, str.rend(), ::isalpha);
	return distance(a, b);
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇LeetCode-Binary Tree Inorder Tr.. 下一篇grunt学习笔记(适用初学者)

评论

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

·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)
·SQL CREATE INDEX 语 (2025-12-25 01:21:45)
·Shell 传递参数 (2025-12-25 00:50:45)
·Linux echo 命令 - (2025-12-25 00:50:43)