LeetCode 5689. Count the number of items matching the search rules

Give you an array of items, where items[i] = [typei, colori, namei], describing the type, color, and name of the i-th item.

Also give you a retrieval rule represented by two strings ruleKey and ruleValue.

If the i-th article can meet one of the following conditions, it is considered to match the given search rule:

ruleKey == "type" and ruleValue == typei.
ruleKey == "color" and ruleValue == colori.
ruleKey == "name" and ruleValue == namei.
Count and return the number of items matching the retrieval rules.

Create a mapping from ruleKey to subscript, and then traverse:

class Solution {
    
    
public:
    int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
    
    
        unordered_map<string, int> keyToIndex = {
    
    {
    
    "type", 0}, {
    
    "color", 1}, {
    
    "name", 2}};
        
        int count = 0;
        for (vector<string> &svec : items) {
    
    
            if (svec[keyToIndex[ruleKey]] == ruleValue) {
    
    
                ++count;
            }
        }
        return count;
    }
};

Guess you like

Origin blog.csdn.net/tus00000/article/details/114240361