[LeetCode] Count Items Matching a Rule

1773. Count 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.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
int pos = ruleKey == "type" ? 0 : ruleKey == "color" ? 1 : 2, res = 0;
for(auto& item : items) {
if(item[pos] == ruleValue)
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/28/PS/LeetCode/count-items-matching-a-rule/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.