난이도: 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.
A 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
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 1400. Construct K Palindrome Strings (Python) (0) | 2025.01.11 |
---|---|
[LeetCode] 916. Word Subsets (Python) (0) | 2025.01.10 |
[LeetCode] 3042. Count Prefix and Suffix Pairs I (Python) (1) | 2025.01.08 |
[LeetCode] 1408. String Matching in an Array (Python) (0) | 2025.01.07 |
[LeetCode] 1769. Minimum Number of Operations to Move All Balls to Each Box (Python) (0) | 2025.01.06 |