目录
题目
给你一个数组 items ,其中 items[i] = [typei, colori, namei] ,描述第 i 件物品的类型、颜色以及名称。
另给你一条由两个字符串 ruleKey 和 ruleValue 表示的检索规则。
如果第 i 件物品能满足下述条件之一,则认为该物品与给定的检索规则 匹配 :
ruleKey == "type" 且 ruleValue == typei 。
ruleKey == "color" 且 ruleValue == colori 。
ruleKey == "name" 且 ruleValue == namei 。
统计并返回 匹配检索规则的物品数量 。
示例 1:
输入:items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
输出:1
解释:只有一件物品匹配检索规则,这件物品是 ["computer","silver","lenovo"] 。
示例 2:
输入:items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
输出:2
解释:只有两件物品匹配检索规则,这两件物品分别是 ["phone","blue","pixel"] 和 ["phone","gold","iphone"] 。注意,["computer","silver","phone"] 未匹配检索规则。
提示:
1 <= items.length <= 104
1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
ruleKey 等于 "type"、"color" 或 "name"
所有字符串仅由小写字母组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-items-matching-a-rule
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解决方案
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
int index =0;
int num;
if(ruleKey[0] == 'c')
{
index =1;
}
if(ruleKey[0] == 'n')
{
index =2;
}
for(auto e:items)
{
if(e[index]== ruleValue)
{
num++;
}
}
return num;
}
};
通过判断 ruleKey中type,clour,name的首字母将其分别当做下标0,1,2,在遍历中检测是否符合 ruleValue的值。
C++11中for(auto e:string)相当于遍历string字符串,每个字符的值存带变量e中,这个e只可以访问不可以修改,而for(auto& e:string)可以通过e修改对应的值,这个用法可以快速遍历字符串,数组等。
优化
可以通过三目运算符进行简化,同时使用count_if函数(按条件统计容器中元素个数)。
count_if函数语法:
count_if( *_begin() , *_end() , _pred),其中 *_begin()是容器的头, *_end() 是容器的尾,_pred是一个用于判断的布尔值函数。
而在优化中 [&](auto e) { return e[index] == ruleValue; }是一个Lambda表达式,可以直接在需要调用函数的位置定义短小精悍的函数,而不需要预先定义好函数。[ ]中为数据的捕获列表,用来捕获上下文的数据。该题中(auto e)表示捕获的每一个items作为参数。
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
int index =0;
int num;
index = (ruleKey[0] == 't')? 0:(ruleKey[0] == 'c'?1:2);
return count_if(items.begin(), items.end(), [&](auto e) { return e[index] == ruleValue; });
}
};