LeetCode題解(0434):統計字符串中的單詞數(Python)

題目:原題鏈接(簡單)

解法 執行用時
Ans 1 (Python) 36ms (86.67%) - 56ms (6.24%)
Ans 2 (Python) 36ms (86.67%) - 40ms (66.99%)

LeetCode的Python執行用時隨緣,只要時間複雜度沒有明顯差異,執行用時一般都在同一個量級,僅作參考意義。

解法一(Pythonic):

def countSegments(self, s: str) -> int:
    return sum([1 for i in re.split(" +", s) if len(i) > 0])

解法二(遍歷):

def countSegments(self, s: str) -> int:
    not_space = False
    ans = 0
    for c in s:
        if c != " ":
            not_space = True
        else:
            if not_space:
                ans += 1
                not_space = False
    ans += not_space
    return ans
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章