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"
andruleValue == typei
.ruleKey == "color"
andruleValue == colori
.ruleKey == "name"
andruleValue == namei
.
Find the number of items that match the given rule.
Example:
Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output: 1
Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].
Approach:
C++
#include <bits/stdc++.h>using namespace std;int countMatches(vector<vector<string>> &items,string ruleKey, string ruleValue){int count = 0;for (int i = 0; i < items.size(); i++){string typei = items[i][0];string colori = items[i][1];string namei = items[i][2];if (ruleKey == "type" && ruleValue == typei)count++;else if (ruleKey == "color" && ruleValue == colori)count++;else if (ruleKey == "name" && ruleValue == namei)count++;}return count;}int main(){vector<vector<string>> items = {{"phone", "blue", "pixel"},{"computer", "silver", "lenovo"},{"phone", "gold", "iphone"}};string ruleKey = "color", ruleValue = "silver";cout << countMatches(items, ruleKey, ruleValue);return 0;}
No comments:
Post a Comment