Leetcode 58. Length of Last Word

两个点:

  1. str.strip()  : 去除字符串两边的空格
    str.lstrip() : 去除字符串左边的空格
    str.rstrip() : 去除字符串右边的空格

    注:此处的空格包含' ', ' ',  ' ',  ' '
  2. for i in range(size-1,-1,-1)倒序遍历的写法
class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        s=s.strip()
        ans=0
        size=len(s)
        for i in range(size-1,-1,-1):
            if s[i]==' ':
                return ans
            else:
                ans+=1
        return ans
        
原文地址:https://www.cnblogs.com/zywscq/p/10514243.html