leetcode 58.最后一个单词的长度(python版)

需求

给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = “Hello World”
输出:5
解释:最后一个单词是“World”,长度为5。
示例 2:
输入:s = " fly me to the moon "
输出:4
解释:最后一个单词是“moon”,长度为4。
示例 3:
输入:s = “luffy is still joyboy”
输出:6
解释:最后一个单词是长度为6的“joyboy”。

代码

class Solution:
    def last_word_length(self,str):
        # strip() 去除首尾空格, split(" "),以空格拆分
        str_split=str.strip().split(" ")
        # print(str_split)
        # str_split[-1]获取拆分后的最后一个元素
        new_str=str_split[-1]
        # print(new_str)
        return len(new_str)
if __name__ == '__main__':
    call=Solution()
    str1="hello world"
    str2 = "   fly me   to   the moon  "
    print(f"{str1}最后一个单词长度为:",call.last_word_length(str1))
    print(f"{str2}最后一个单词长度为:",call.last_word_length(str2))

运行结果

leetcode 58.最后一个单词的长度(python版)_第1张图片

你可能感兴趣的:(leetcode,python,算法)