|
| 1 | +// Source : https://leetcode.com/problems/count-items-matching-a-rule/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-03-14 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * You are given an array items, where each items[i] = [typei, colori, namei] describes the type, |
| 8 | + * color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and |
| 9 | + * ruleValue. |
| 10 | + * |
| 11 | + * The ith item is said to match the rule if one of the following is true: |
| 12 | + * |
| 13 | + * ruleKey == "type" and ruleValue == typei. |
| 14 | + * ruleKey == "color" and ruleValue == colori. |
| 15 | + * ruleKey == "name" and ruleValue == namei. |
| 16 | + * |
| 17 | + * Return the number of items that match the given rule. |
| 18 | + * |
| 19 | + * Example 1: |
| 20 | + * |
| 21 | + * Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], |
| 22 | + * ruleKey = "color", ruleValue = "silver" |
| 23 | + * Output: 1 |
| 24 | + * Explanation: There is only one item matching the given rule, which is |
| 25 | + * ["computer","silver","lenovo"]. |
| 26 | + * |
| 27 | + * Example 2: |
| 28 | + * |
| 29 | + * Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], |
| 30 | + * ruleKey = "type", ruleValue = "phone" |
| 31 | + * Output: 2 |
| 32 | + * Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] |
| 33 | + * and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match. |
| 34 | + * |
| 35 | + * Constraints: |
| 36 | + * |
| 37 | + * 1 <= items.length <= 104 |
| 38 | + * 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10 |
| 39 | + * ruleKey is equal to either "type", "color", or "name". |
| 40 | + * All strings consist only of lowercase letters. |
| 41 | + ******************************************************************************************************/ |
| 42 | + |
| 43 | +class Solution { |
| 44 | +public: |
| 45 | + int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) { |
| 46 | + int idx; |
| 47 | + switch(ruleKey[0]) { |
| 48 | + case 't': idx = 0; break; |
| 49 | + case 'c': idx = 1; break; |
| 50 | + case 'n': idx = 2; break; |
| 51 | + default: return 0; |
| 52 | + } |
| 53 | + |
| 54 | + int cnt = 0; |
| 55 | + for (auto& item : items) { |
| 56 | + if (item[idx] == ruleValue) cnt++; |
| 57 | + } |
| 58 | + return cnt; |
| 59 | + } |
| 60 | +}; |
0 commit comments