771. Jewels and Stones

本文介绍了一种计算特定类型宝石(即珠宝)在给定石头集合中出现次数的方法。通过两种不同的算法实现,包括直接遍历比较和使用HashSet进行高效查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:

You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so “a” is considered a different type of stone from “A”.

Example1:

Input: J = “aA”, S = “aAAbbbb”
Output: 3

Example2:

Input: J = “z”, S = “ZZ”
Output: 0

Note:

  • S and J will consist of letters and have length at most 50.
  • The characters in J are distinct.

Solution:

问题解析:
对于代表石头的字符串S中,每个字母看做一种宝石,那么这个问题就是计算出字符串J中的每个字符在字符串中出现的次数和,其中区分大小写。
思路一:
最笨的思路,遍历字符串S和字符串J,如果字符相同则计数加1
时间复杂度O(J.length*S.length)
空间复杂度O(1)

int sum = 0;
for(char j : J.toCharArray())
{
    for(char s : S.toCharArray())
    {
        if(s == j){
            sum ++;
        }
    }
}

思路二:
利用HashSet这个结构,将宝石作为HashSet的键值key,再遍历字符串S,HashSet中是否已存在这些key值
时间复杂度O(J.length + S.length)
空间复杂度:O(J.length)

class Solution {
    public int numJewelsInStones(String J, String S) {
        int sum = 0;
        Set jewel = new HashSet();
        for(char c : J.toCharArray()){
            jewel.add(c);
        }
        for(char c : S.toCharArray()){
            if(jewel.contains(c)){
                sum ++;
            }
        }
        return sum;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值