래원

[LeetCode] 2185. Counting Words With a Given Prefix (Python) 본문

알고리즘/LeetCode

[LeetCode] 2185. Counting Words With a Given Prefix (Python)

Laewon Jeong 2025. 1. 9. 16:38

 

난이도: Easy

 

문제 설명


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.

 

prefix of a string s is any leading contiguous substring of s.

 

문제 예제


Example 1:

Input: words = ["pay","attention","practice","attend"],pref= "at"
Output: 2
Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend".

Example 2:

Input: words = ["leetcode","win","loops","success"],pref= "code"
Output: 0
Explanation: There are no strings that contain "code" as a prefix.

 

제한 사항


  • 1 <= words.length <= 100
  • 1 <= words[i].length, pref.length <= 100
  • words[i] and pref consist of lowercase English letters.

 

Solution(솔루션)


class Solution:
    def prefixCount(self, words: List[str], pref: str) -> int:
        answer = 0

        for word in words:
            if word.startswith(pref):
                answer += 1
        
        return answer

 

요즘 계속 Easy 문제만 daily question으로 내는 것 같다...

 

이 문제는 startswith를 사용해 해결했다. words의 모든 요소에 대해서 word.startswith(pref)를 하고 이것이 True를 반환한다면 answer +1 해주었다.

 

마지막에는 answer를 return 하고 정답을 맞출 수 있었다.


문제: 2185. Counting Words With a Given Prefix

 

깃허브: github

 

algorithm_practice/LeetCode/2292-counting-words-with-a-given-prefix at main · laewonJeong/algorithm_practice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithm_practice development by creating an account on GitHub.

github.com