1、题目
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