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
相关推荐
TracyCoder1231 天前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
u0109272711 天前
C++中的策略模式变体
开发语言·c++·算法
2501_941837261 天前
停车场车辆检测与识别系统-YOLOv26算法改进与应用分析
算法·yolo
六义义1 天前
java基础十二
java·数据结构·算法
四维碎片1 天前
QSettings + INI 笔记
笔记·qt·算法
Tansmjs1 天前
C++与GPU计算(CUDA)
开发语言·c++·算法
独自破碎E1 天前
【优先级队列】主持人调度(二)
算法
weixin_445476681 天前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
打工的小王1 天前
LeetCode Hot100(一)二分查找
算法·leetcode·职场和发展
Swift社区1 天前
LeetCode 385 迷你语法分析器
算法·leetcode·职场和发展