victory的博客

长安一片月,万户捣衣声

0%

leetcode | 字符串中的单词数

434.字符串中的单词数

题目描述

统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。

题目链接

思路

1.使用语言内置函数split()
2.原地法
计算单词的数量,就等同于计数单词开始的下标个数。因此,只需要定义好下标的条件,就可以遍历整个字符串,检测每个下标。定义如下:若该下标前为空格(或者为初始下标),且自身不为空格,则其为单词开始的下标。该条件可以以常数时间检测。最后,返回满足条件的下标个数。

代码

class Solution:
    def countSegments(self, s: str) -> int:
        list_s = s.split(' ')
        for i in range(list_s.count('')):
            list_s.remove('')
        if not list_s:
            return 0
        return len(list_s)

    def countSegments1(self, s):
        return len(s.split())

    def countSegments2(self, s):
        segment_count = 0

        for i in range(len(s)):
            if (i == 0 or s[i-1] == ' ') and s[i] != ' ':
                segment_count +=1

        return segment_count


if __name__ == '__main__':
    slt = Solution()
    # s = "      "
    s = "The one-hour drama series Westworld is a dark odyssey about the dawn of artificial consciousness and the evolution of sin. Set at the intersection of the near future and the reimagined past, it explores a world in which every human appetite, no matter how noble or depraved, can be indulged."
    res = slt.countSegments2(s)
    print(res)

    # 分割文本
    # s = "The sky is very blue."
    # words = s.split(" ")
    # print(words)