题目:
Given a string s, return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.
给定一个字串,判断里面有几个segment
segment指无空白的连续字元(像是单字)
ex:input:"Hello, my name is John"=>output:5
explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
先写个比较正规的写法
class Solution: def countSegments(self, s: str) -> int: ans=0 i=0 while i<len(s): if s[i]!=" ": ans=ans+1 while i<len(s) and s[i]!=" ": i=i+1 else: i=i+1 return ans
遍历该字串
遇到非空白字元ans就+1,接着让i脱离该segment再继续往下走
直到完全遍历,回传ans
最后执行时间34ms(faster than 85.49%)
当然应该也不少人发现这题在python其实异常轻鬆
class Solution: def countSegments(self, s: str) -> int: s=s.split() return len(s)
将字串split,回传split出来的阵列长度即可
最后执行时间24ms(faster than 98.76%)
那我们下题见