【LeetCode每天一题】Length of Last Word(字符串中最后一个单词的长度)
2024-09-14 20:10:32
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.
Example:
Input: "Hello World"
Output: 5 思路
这道题挺简单的,因为我使用的是python,所以可以直接使用内建方法来解决该问题。就是先将字符串首尾的空格去除,然后使用空格对字符串对其进行分割得到一个列表,直接返回最后一个元素的长度。就得到答案。
另外如果我们不使用内建方法的话,可以从最后末尾来进行遍历,当然先清除空字符,然后开始计数,遇到空格时直接返回所记得数,就得到结果。
解决代码
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip()
if len(s) == 0:
return 0
word_list = s.split(' ')
return len(word_list[-1])
最新文章
- CString用法小结《转载》
- Java selenium web页面的滚动条操作
- FusionCharts简单教程(四)-----基本数字格式
- ASP.NET Core 1.0到底是什么?
- 解决eclipse使用Search弹出错误问题
- dll 打包
- 数据库知识(主要基于Oracle,Sql可参考)
- Redis 脚本
- jquery在线引用的地址
- zookeeper[6] zookeeper FAQ(转)
- 类似的微博推断客户关系sql声明
- 【转】判断URL是否能够访问
- apache2修改用户和组
- Centos下安装git的web服务器
- Centos7-安装telnet服务
- SQL Server数据库————连接查询和分组查询
- 在线学习在CTR上应用的综述
- [转帖]nginx配置ssl加密(单/双向认证、部分https)
- 堵上NFine SubmitForm漏洞
- Vijos1982 NOIP2015Day2T2 子串 substring 动态规划