LeetCode-58. Length of Last Word

本文提供了一种解决LeetCode上“最后一个单词的长度”问题的方法,通过Python实现,展示了如何有效地找到并计算字符串中最后一个单词的长度,包括去除尾部空白字符及识别单词边界的技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

评论区最多的就是it's no fun at all!哈哈哈

题目:

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"
Output: 5

solution:

class Solution:
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s is None:
            return 0
        j = s.strip().split(' ')

        return len(j[-1])



当然也有那么一些大佬愿意不用函数:

用==' '或者.isspace()来判断最后一个空格后的那个单词的长度:

def lengthOfLastWord(self, s):
    ls = len(s)
    # slow and fast pointers
    slow = -1
    # iterate over trailing spaces
    while slow >= -ls and s[slow] == ' ':
        slow-=1
    fast = slow
    # iterate over last word
    while fast >= -ls and s[fast] != ' ':
        fast-=1
    return slow - fast
def lengthOfLastWord(self, s):
    # (going backwards) find first non-space char
    for i in range(len(s) - 1, -2, -1):
        if i == -1 or s[i] != " ":
            break
    
    # keep going until a space or end of string
    for j in range(i, -2, -1):
        if j == -1 or s[j] == " ":
            return i - j

对不起,我庸俗~~~

等待大佬们去丰富吧https://leetcode.com/problems/length-of-last-word/discuss/21961/My-36-ms-Python-solution



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值