[LeetCode] Counting Words With a Given Prefix

아르당·2026년 8월 14일

LeetCode

목록 보기
465/626
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

문자열 배열 words와 문자열 pref가 주어진다.
words에서 접두어가 pref인 문자열의 수를 반환해라.
문자열 s의 접두어는 s의 부분 문자열이다.

Example

#1
Input: words = ["pay", "attention", "practice", "attend"], pref = "at"
Output: 2
Explanation: 2개의 문자열 "attention", "attend"는 접두어에 "at"을 포함한다.

#2
Input: word = ["leetcode", "win", "loops", "success"], pref = "code"
Output: 0
Explanation: 접두어로 "code"를 포함하는 문자열은 없다.

Constraints

  • 1 <= words.length <= 100
  • 1 <= words[i].length, pref.length <= 100
  • words[i]와 pref는 영어 소문자로 구성된다.

Solved

class Solution {
    public int prefixCount(String[] words, String pref) {
        int count = 0;
        
        for(String word : words){
            if(word.length() >= pref.length() && word.substring(0, pref.length()).equals(pref)){
                count++;
            }
        }

        return count;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글