LeetCode | 434.字符串中的单词数

这道题直接使用语言内置的 split 函数可直接分离出字符串中的每个单词,但是要注意区分两种情况:1、空串;2、多个空格连续,分割后会出现空字符的情况,应该舍弃

python 复制代码
class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s == '':
            return 0
        ss = s.split(" ")
        count = 0
        for i in range(len(ss)):
            if len(ss[i]) != 0:
                count += 1
        return count

题解有另外一种解法

python 复制代码
class Solution:
    def countSegments(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
相关推荐
漫随流水21 小时前
leetcode算法(151.反转字符串中的单词)
数据结构·算法·leetcode
ada7_1 天前
LeetCode(python)78.子集
开发语言·数据结构·python·算法·leetcode·职场和发展
DeepVis Research1 天前
【AGI/Simulation】2026年度通用人工智能图灵测试与高频博弈仿真基准索引 (Benchmark Index)
大数据·人工智能·算法·数据集·量化交易
努力学算法的蒟蒻1 天前
day52(1.3)——leetcode面试经典150
算法·leetcode·面试
leoufung1 天前
LeetCode 97. 交错字符串 - 二维DP经典题解(C语言实现)
c语言·算法·leetcode
leiming61 天前
c++ map容器
开发语言·c++·算法
杨校1 天前
杨校老师课堂备赛C++信奥之模拟算法习题专项训练
开发语言·c++·算法
世洋Blog1 天前
AStar算法基础学习总结
算法·面试·c#·astar·寻路
haing20191 天前
七轴协作机器人运动学正解计算方法
算法·机器学习·机器人