【LeetCode每日一题】【字符串/数组】2022-10-29 1773. 统计匹配检索规则的物品数量 Java实现


题目链接

https://leetcode.cn/problems/count-items-matching-a-rule/

题目

在这里插入图片描述

我的思路

循环遍历外层List

如果ruleKey的值是type,那么取出每个List的第一个元素(下标为0的元素),并且比较与ruleValue的值是否相等,若相等,则计数加一;

如果ruleKey的值是color,那么取出每个List的第二个元素(下标为1的元素),并且比较与ruleValue的值是否相等,若相等,则计数加一;

如果ruleKey的值是name,那么取出每个List的第三个元素(下标为2的元素),并且比较与ruleValue的值是否相等,若相等,则计数加一;

import java.util.List;

class Solution {
    public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {

        int cnt = 0;
        for (List<String> item : items) {
            if ("type".equals(ruleKey)) {
                if (item.get(0).equals(ruleValue)) {
                    cnt++;
                }
            } else if ("color".equals(ruleKey)) {
                if (item.get(1).equals(ruleValue)) {
                    cnt++;
                }
            } else if ("name".equals(ruleKey)) {
                if (item.get(2).equals(ruleValue)) {
                    cnt++;
                }
            }
        }
        return cnt;
    }
}

在这里插入图片描述

官方思路

可以利用哈希表把输入ruleKey转换为items[i]的下标,然后再遍历一遍items,找出符合条件的物品数量

官方提供的代码要比我写的简洁许多,可以参考

import java.util.HashMap;
import java.util.List;

class Solution {
    public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
        int index = new HashMap<String, Integer>() {
            {
                put("type", 0);
                put("color", 1);
                put("name", 2);
            }
        }.get(ruleKey);

        int cnt = 0;
        for (List<String> item : items) {
            if (item.get(index).equals(ruleValue)) {
                cnt++;
            }
        }
        return cnt;
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值