Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

A word is a maximal substring consisting of non-space characters only.

Example 1:
Input: s = "Hello World"
Output: 5

Example 2:
Input: s = " "
Output: 0

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of only English letters and spaces ' '.

Solution in python:

class Solution:
    def lengthOfLastWord(self, s: str) -> int:       
        slist = s.split()
        if len(slist) == 0:
            return 0
        else:
            return len(slist[-1])
class Solution:
    def lengthOfLastWord(self, s: str) -> int:       
        right = len(s)
        while right > 0 and s[right-1] == ' ':
            right -= 1
        left = right
        while left > 0 and s[left-1] != ' ':
            left -= 1
        return right - left
最后修改日期: 2020年12月26日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。