개발 일지
1773. Count Items Matching a Rule (규칙과 일치하는 항목 수) 본문
배열 items가 주어지는데, 여기서 items[i] = [typei, colori, namei]는 i번째 항목의 유형, 색상 및 이름을 설명합니다. 또한 'ruleKey'와 'ruleValue'의 두 문자열로 표시되는 규칙이 주어집니다.
i번째 항목은 다음 중 하나가 사실인 경우 규칙과 일치한다고 합니다:
- ruleKey == "type" and ruleValue == typei.
- ruleKey == "color" and ruleValue == colori.
- ruleKey == "name" and ruleValue == namei.
주어진 규칙과 일치하는 항목의 수를 반환합니다.
예시 1:
입력: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
출력: 1
설명: 주어진 규칙과 일치하는 item은 ["computer","silver","lenovo"] 하나뿐입니다..
예시 2:
입력: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
출력: 2
설명: 주어진 규칙과 일치하는 item은 ["phone","blue","pixel"] 과 ["phone","gold","iphone"]. 두 가지뿐입니다. item["computer","silver","phone"]은 일치하지 않습니다.
조건:
- 1 <= items.length <= 10^4
- 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
- ruleKey는 "type", "color", 또는 "name"과 동일합니다.
- 모든 문자열은 소문자로만 구성됩니다.
정답:
public class Solution {
public int CountMatches(IList<IList<string>> items, string ruleKey, string ruleValue) {
List<string> result = new List<string>();
List<string> keys = new List<string> { "type", "color", "name" };
int ruleKeyNum = keys.IndexOf(ruleKey);
for (int i = 0; i < items.Count; i++)
{
result.Add(items[i][ruleKeyNum]);
}
return result.Count(n => n == ruleValue);
}
}
해설: 정해져있는 ruleKey의 종류를 keys에 옮겨 둔 후 IndexOf를 이용하여 위치를 확인한 후 result에 해당 종류의 아이템을 모두 추가합니다.그리고 result내의 ruleValue와 동일한 값의 개수를 찾아 return합니다.