设为首页 加入收藏

TOP

Leetcode 细节实现 Length of Last Word
2015-07-20 17:44:12 来源: 作者: 【 】 浏览:2
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学习笔记(适用初学者)

评论

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

·MySQL 安装及连接-腾 (2025-12-25 06:20:28)
·MySQL的下载、安装、 (2025-12-25 06:20:26)
·MySQL 中文网:探索 (2025-12-25 06:20:23)
·Shell脚本:Linux Sh (2025-12-25 05:50:11)
·VMware虚拟机安装Lin (2025-12-25 05:50:08)