[LeetCode] Count Items Matching a Rule

아르당·2026년 6월 28일

LeetCode

목록 보기
379/561
post-thumbnail

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

Problem

배열 items가 주어지고, 각 items[i]는 [typei, colori, namei]으로 i번째 아이템의 유형, 색, 이름을 나타낸다. 또한 ruleKey와 ruleValue 두 개의 문자열로 표현되는 규칙이 주어진다.

다음 중 하나가 true면 i번째 규칙에 부합하다.

  • ruleKey == "type"이면 ruleValue = typei
  • ruleKey == "color"이면 ruleValue = colori
  • ruleKey == "name"이면 ruleValue = namei

주어진 규칙에 맞는 아이템의 갯수를 반환해라.

Example

#1
Input: items = [["phone", "blue", "pixel"], ["computer", "silver", "lenovo"], ["phone", "gold", "iphone"]], ruleKey = "color", ruleValue = "silver"
Output: 1
Explanation: ["computer", "silver", "lenovo"] 하나만 규칙에 맞는 아이템이다.

#2
Input: items = [["phone", "blue", "pixel"], ["computer", "silver", "phone"], ["phone", "gold", "iphone"]], ruleKey = "type", ruleValue = "phone"
Output: 2
Explanation: ["phone", "blue", "pixel"]과 ["phone", "gold", "iphone"] 2개만 규칙에 맞는 아이템이다. 아이템 ["computer", "silver", "phone"]은 맞지 않다.

Constraints

  • 1 <= items.length <= 10^4
  • 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
  • ruleKey는 "type", "color", "name" 중 하나이다.
  • 모든 문자열은 오직 영어 소문자로 구성된다.

Solved

class Solution {
    public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
        int index = ruleKey.equals("type") ? 0 : ruleKey.equals("color") ? 1 : 2;
        int count = 0;

        for(List<String> item : items){
            if(item.get(index).equals(ruleValue)){
                count++;
            }
        }

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

0개의 댓글