LeetCode练题——58. Length of Last Word

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方法

扫描二维码关注公众号,回复: 8997705 查看本文章
 1 # -*- coding: utf-8 -*-
 2 # @Time    : 2020/2/7 20:41
 3 # @Author  : SmartCat0929
 4 # @Email   : [email protected]
 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 "))

猜你喜欢

转载自www.cnblogs.com/Smart-Cat/p/12274931.html