題目:
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%)
那我們下題見