【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