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
相关推荐
ForeverYang201517 分钟前
一种无需训练缺陷数据生成算法--O2MAG
人工智能·深度学习·算法
xuxigifxfh1 小时前
牛客:HJ170 01序列
java·开发语言·算法·华为机考
朝朝辞暮i1 小时前
C++ 第 33 课:事件循环——spin() 到底在干什么
开发语言·c++·算法
殷色玫瑰1 小时前
AVL树:从平衡因子到四种旋转的完整实现
c语言·数据结构·c++·算法·visualstudio
jidaowansui2 小时前
B3643 图的存储———>数组模拟邻接矩阵
算法
y1su2 小时前
Leetcode 二分模板
java·数据结构·算法·leetcode·排序算法
youshi66682 小时前
平衡车——PID算法优化
stm32·单片机·嵌入式硬件·算法·pid·平衡车
聪明蛋子哟3 小时前
不仅仅是向量检索:结合知识图谱与Tool Calling的混合增强生成(Hybrid RAG)方案
人工智能·算法·知识图谱
Pniubi3 小时前
力扣55跳跃游戏(贪心)
算法·leetcode·游戏
jyyyx的算法博客4 小时前
传球游戏【思维】
算法