題目出處
源自于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
解讀
計(jì)算給定字符串的片段數(shù),片段由空白字符分割。
如給定:"Hello, my name is John"
, 輸出5(五個(gè)片段,分別為"Hello,"
, "my"
, "name"
, "is"
, "John"
解答
此題用python做太簡單了,split字符串得到list,計(jì)算list長度即可。
代碼
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split())
排名
第二版
思路解析
在第一版中,直接使用python的str類提供的函數(shù),效率比較低,下面使用模式計(jì)算片段數(shù)量:
- 用
space_mode
變量表示是否處于空白字符模式(空白字符是片段分割符); - 如果處于空白字符模式(
space_mode = True
),遇到非空字符時(shí),片段數(shù)加一; - 如果不處于空白字符模式(
space_mode = False
),遇到空白字符,則轉(zhuǎn)入空白字符模式
代碼如下
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
排名
后續(xù)工作
此題用C語言做比較能領(lǐng)會split的核心概念:
- 用C語言解答此題;
- 研究python的
str.split()
方法。