首页 > 其他 > 详细

LeetCode练题——58. Length of Last Word

时间:2020-02-07 23:57:40      阅读:92      评论:0      收藏:0      [点我收藏+]

1、题目

 

58. Length of Last Word——Easy

 

Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"
Output: 5

 

2、我的解法

先采用strip方法

 

 1 # -*- coding: utf-8 -*-
 2 # @Time    : 2020/2/7 20:41
 3 # @Author  : SmartCat0929
 4 # @Email   : 1027699719@qq.com
 5 # @Link    : https://github.com/SmartCat0929
 6 # @Site    : 
 7 # @File    : 58. Length of Last Word.py
 8 
 9 class Solution:
10     def lengthOfLastWord(self, s: str) -> int:
11         s1=s.strip()
12         lens = len(s1)
13         if lens > 0:
14             list1 = []
15             for i in range(lens):
16                 if s1[i] == " ":
17                     list1.append(i)
18             if len(list1) > 0:
19                 a = list1.pop()
20                 return lens - 1 - a
21             else:
22                 return lens
23         else:
24             return 0
25 print(Solution().lengthOfLastWord("a "))

 

LeetCode练题——58. Length of Last Word

原文:https://www.cnblogs.com/Smart-Cat/p/12274931.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!