【LeetCode每天一题】Length of 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.

Example:

Input: "Hello World"
Output: 5

思路

     这道题挺简单的,因为我使用的是python,所以可以直接使用内建方法来解决该问题。就是先将字符串首尾的空格去除,然后使用空格对字符串对其进行分割得到一个列表,直接返回最后一个元素的长度。就得到答案。
  另外如果我们不使用内建方法的话,可以从最后末尾来进行遍历,当然先清除空字符,然后开始计数,遇到空格时直接返回所记得数,就得到结果。
解决代码

 
 
 1 class Solution(object):
 2     def lengthOfLastWord(self, s):
 3         """
 4         :type s: str
 5         :rtype: int
 6         """
 7         s  = s.strip()
 8         if len(s) == 0:
 9             return 0
10         word_list = s.split(' ')
11         return len(word_list[-1])
12         
 
 

 




转载于:https://www.cnblogs.com/GoodRnne/p/10746179.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值