leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 2d159f42638f87dfca97a0ab50099b0eef651e5e
parent 04d1609e0d5f554d23c19bc0629d0c3d697a87a1
Author: Jack Sangdahl <jack@pngu.org>
Date:   Thu,  9 Jan 2025 09:37:42 +0100

2185. counting words with a given prefix

Diffstat:
Acounting_words_given_prefix.c | 23+++++++++++++++++++++++
Acounting_words_given_prefix.py | 27+++++++++++++++++++++++++++
2 files changed, 50 insertions(+), 0 deletions(-)

diff --git a/counting_words_given_prefix.c b/counting_words_given_prefix.c @@ -0,0 +1,23 @@ +// 2185. Counting Words With a Given Prefix +#include "leetcode.h" + +/* + * you are given an array of strings 'words' and a string 'pref'. return the + * number of strings in 'words' that contain 'pref' as a prefix. a prefix of a + * string 's' is any leading contiguous substring of 's'. + */ + +int prefixCount(char **words, int wordsSize, char *pref) { + int cnt = 0, n = strlen(pref); + for (int i = 0; i < wordsSize; i++) + if (!strncmp(words[i], pref, n)) + cnt++; + return cnt; +} + +int main() { + char *w1[] = {"pay", "attention", "practice", "attend"}, *p1 = "at"; + char *w2[] = {"leetcode", "win", "loops", "success"}, *p2 = "code"; + printf("%d\n", prefixCount((char **)w1, ARRAY_SIZE(w1), p1)); // expect: 2 + printf("%d\n", prefixCount((char **)w2, ARRAY_SIZE(w2), p2)); // expect: 0 +} diff --git a/counting_words_given_prefix.py b/counting_words_given_prefix.py @@ -0,0 +1,27 @@ +# 2185. Counting Words With a Given Prefix + +""" +you are given an array of strings 'words' and a string 'pref'. return the +number of strings in 'words' that contain 'pref' as a prefix. a prefix of a +string 's' is any leading contiguous substring of 's'. +""" + + +class Solution(object): + def prefixCount(self, words, pref): + """ + :type words: List[str] + :type pref: str + :rtype: int + """ + cnt = 0 + for i in words: + if i.startswith(pref): + cnt += 1 + return cnt + + +if __name__ == "__main__": + obj = Solution() + print(obj.prefixCount(words=["pay", "attention", "practice", "attend"], pref="at")) + print(obj.prefixCount(words=["leetcode", "win", "loops", "success"], pref="code"))