LeetCode ❀ 58. 最後の単語の長さ/Pythonのsplit()関数

トピック:

文字列 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”。

答え:

例 2 からわかるように、文字列の末尾にスペースが含まれる場合があります。

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        i, count = len(s) - 1, 0
        while i >= 0 and s[i] == ' ':
            i -= 1
        while i >= 0:
            if s[i] == ' ':return count
            count += 1
            i -= 1
        return count

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.split()[-1])

 # 还有一种方法就是使用 split() 函数
 # split() 通过指定分隔符对字符串进行切片,如果第二个参数 num 有指定值,则分割为 num+1 个子字符串。
 # split("x", 2)则表示以x为分隔符,将字符串分成3个,从前往后分割依次
 # 在此题中,分割完再以[-1]取最后一个字符串再计算长度

おすすめ

転載: blog.csdn.net/qq_42395917/article/details/126593824