728x90
반응형
✨ 문제
Counting Items Matching a Rule
You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.
The ith item is said to match the rule if one of the following is true:
- ruleKey == "type" and ruleValue == typei.
- ruleKey == "color" and ruleValue == colori.
- ruleKey == "name" and ruleValue == namei.
Return the number of items that match the given rule.
https://leetcode.com/problems/count-items-matching-a-rule/description/
✨ 최종코드
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
int count = 0;
int index = 0;
// type, color, name
// [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
if (ruleKey.equals("color"))
index = 1;
else if (ruleKey.equals("name"))
index = 2;
for (List<String> item : items) {
if (item.get(index).equals(ruleValue))
count++;
}
return count;
}
}
ruleKey와 ruleValue가 일치하는 값을 저장할 변수 count와 ruleKey의 인덱스를 저장할 변수 index를 선언했다.
items의 데이터 순서가 type, color, name이기 때문에 index에 ruleKey가 type이면 0, color면 1, name이면 2를 넣어줬다.
index값 지정 후 for문으로 items의 데이터들을 순회하며 각 데이터의 index에 들어있는 값이 ruleValue와 일치하면 count를 증가시켜 주었다.
마지막으로 rulekey와 ruleValue가 일치하는 데이터의 수가 저장된 count를 리턴해주었다.
728x90
반응형
'알고리즘 > 99클럽' 카테고리의 다른 글
99클럽 코테 스터디 30일차 TIL + 해시테이블 Hash Table, [leetcode] Decode the Message (0) | 2024.06.20 |
---|---|
99클럽 코테 스터디 29일차 TIL + [leetcode] Shuffle String (0) | 2024.06.18 |
99클럽 코테 스터디 27일차 TIL + [leetcode] Find Words Containing Character (0) | 2024.06.17 |
99클럽 코테 스터디 26일차 TIL +해시 테이블 Hash Table, [leetcode] Number of Good Pairs (0) | 2024.06.16 |
99클럽 코테 스터디 25일차 TIL + [leetcode] Shuffle the Array (0) | 2024.06.15 |