Leetcode 434: Number of Segments in a String

题目出处

源自于leetcode

题目描述

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

For example,

Input: "Hello, my name is John"

Output: 5

解读

计算给定字符串的片段数,片段由空白字符分割。
如给定:"Hello, my name is John", 输出5(五个片段,分别为"Hello,", "my", "name", "is", "John"

解答

此题用python做太简单了,split字符串得到list,计算list长度即可。

代码

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        return len(s.split())
Leetcode 434: Number of Segments in a String_第1张图片
排名

第二版

思路解析

在第一版中,直接使用python的str类提供的函数,效率比较低,下面使用模式计算片段数量:

  1. space_mode变量表示是否处于空白字符模式(空白字符是片段分割符);
  2. 如果处于空白字符模式(space_mode = True),遇到非空字符时,片段数加一;
  3. 如果不处于空白字符模式(space_mode = False),遇到空白字符,则转入空白字符模式

代码如下

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = 0
        space_mode = True # is space

        for c in s:
            # meet a char
            if space_mode and c != ' ':
                count += 1
                space_mode = False

            # meet a space
            if not space_mode and c == ' ':
                space_mode = True

        return count
Leetcode 434: Number of Segments in a String_第2张图片
排名

后续工作

此题用C语言做比较能领会split的核心概念:

  1. 用C语言解答此题;
  2. 研究python的str.split()方法。

你可能感兴趣的:(Leetcode 434: Number of Segments in a String)