今日题目

https://leetcode.com/problems/counting-words-with-a-given-prefix/description

解题思路

按题意直接实现即可!

解法

昨天的题目可以给我们一些启发,帮助我们用最少的代码解决这道题。

复杂度

  • 时间复杂度:$O(N\times L)$,N 为 words 的长度,L 为单个单词的长度。

  • 空间复杂度:$O(1)$,仅使用了若干变量。

代码

class Solution:
    def prefixCount(self, words: List[str], pref: str) -> int:
        ans = 0
        for word in words:
            if word.startswith(pref):
                ans += 1
        return ans