LeetCode 58 Length of Last Word (Python)

Posted by 小明MaxMing on September 15, 2020

题目

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.

解题思路

先strip,如果strip完是空,则返回0,否则返回split之后最后一部分的长度

代码

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        s = s.strip()
        return len(s.split()[-1]) if s else 0

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅