朴素的思维模式是一次遍历:
简单匹配一下,
r
u
l
e
K
e
y
ruleKey
ruleKey和
i
t
e
m
s
items
items的规则,规则匹配,再匹配属性。
直观的简化做法是hash思想:
建立一个
h
a
s
h
m
a
p
hashmap
hashmap,把
r
u
l
e
K
e
y
ruleKey
ruleKey映射为
i
t
e
m
item
item对应属性的下标。题目给出
i
t
e
m
s
[
i
]
=
[
t
y
p
e
i
,
c
o
l
o
r
i
,
n
a
m
e
i
]
items[i] = [typei, colori, namei]
items[i]=[typei,colori,namei],我们要做的,就是把
t
y
p
e
、
c
o
l
o
r
、
n
a
m
e
type、color、name
type、color、name依次映射为
0
,
1
,
2
0,1,2
0,1,2。这一步帮我们省略了规则匹配,接下来只用匹配属性即可。
直接匹配:
// 类型type 颜色color 名称name
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
int ans = 0;
for(int i =0;i<items.size();i++){
if("color"==ruleKey){
if(items[i][1]==ruleValue){
ans++;
}//物品颜色
}else if("type"==ruleKey){
if(items[i][0]==ruleValue){
ans++;
}
}else{//name
if(items[i][2]==ruleValue){
ans++;
}
}
}
return ans;
}
};
哈希表:
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
unordered_map<string,int> hash = {{"type",0},{"color",1},{"name",2}};
int ans = 0,index = hash[ruleKey];
for(auto x:items){
if(x[index] == ruleValue) ans++;
}
return ans;
}
};
理解思路很重要!
欢迎读者在评论区留言,作为日更博主,看到就会回复的。

