LeetCode--Python解析【Length of Last Word】(58)

题目:

方法:

class Solution:
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        temp = s.split(" ")

        while temp:
            x = temp.pop(-1)
            if x:
                return len(x)
            
        return 0

现将s以空格切分,转换为list

再取最后一个非空元素,求长度

如果列表为空,则返回0

猜你喜欢

转载自blog.csdn.net/ZJRN1027/article/details/81188968