【LeetCode每天一题】Length of Last Word(字符串中最后一个单词的长度)

时间:2023-03-09 14:18:34
【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,所以可以直接使用内建方法来解决该问题。就是先将字符串首尾的空格去除,然后使用空格对字符串对其进行分割得到一个列表,直接返回最后一个元素的长度。就得到答案。
  另外如果我们不使用内建方法的话,可以从最后末尾来进行遍历,当然先清除空字符,然后开始计数,遇到空格时直接返回所记得数,就得到结果。
解决代码


 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])