Leetcode第1773题:统计匹配规则的物品数量(Counting items match a rule)

解题思路

根据题意进行模拟即可,利用哈希表把输入的ruleKey转换为items[i]的下标,然后再遍历一遍items,找出符合条件的物品数量。
代码如下:

class Solution {
public:
    int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
        unordered_map<string, int> dictionary = {{"type", 0}, {"color", 1}, {"name", 2}};
        int res = 0, index = dictionary[ruleKey];
        for (auto &&item : items) {
            if (item[index] == ruleValue) {
                res++;
            }
        }
        return res;
    }
};
posted @ 2022-10-29 18:37  hql5  阅读(24)  评论(0)    收藏  举报