Python3 seeking the last word length

Python3 seeking the last word length

Original title: https: //leetcode-cn.com/problems/length-of-last-word/

Given only one case of letters and spaces' String s, which returns the length of the last word. If the string scroll from left to right, then the last word is the last word appears.

If the last word does not exist, 0 is returned.

Description: a word refers only of letters, does not contain any space characters maximum substring.

Example:

输入: "Hello World"
输出: 5

Problem solving:

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        n = len(s)
        word_length = 0
        for i in range(n - 1, -1, -1): #字符串从后往前遍历
            if s[i] == ' ':  #如果遇到空格 分两种情况:1已经找到最后一个单词了 2:未找到最后一个单词
                if word_length:
                    return word_length # 直接返回单词长度
                else:
                    continue #说明还没遇到单词 跳过
            else: #如果遇到不是空格 则最后单词数量+1
                word_length += 1
        return word_length
Published 24 original articles · won praise 0 · Views 419

Guess you like

Origin blog.csdn.net/qq_18138105/article/details/105164942