【LeetCode】771. Jewels and Stones

本文介绍了一种算法,用于计算字符串S中有多少字符出现在字符串J中,即计算S中有多少个字符被视为“宝石”。通过两种不同的Java实现展示了如何解决这个问题。

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

Problem:

You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in Sis 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".


题目:题目大致的意思计算S中的字符出现在J中的数量....

代码1:打败50%多,

class Solution {
    public int numJewelsInStones(String J, String S) {
        if(J.length()==0)
            return 0;
        HashSet<String> hashSet = new HashSet<String>();
        int ret = 0;
        for(int i = 0; i < J.length(); i ++){
        if(!hashSet.contains(J.substring(i, i+1)))
        hashSet.add(J.substring(i,i+1));
        }
        for(int i=0;i<S.length();i++){
            if(hashSet.contains(S.substring(i, i+1))) {
            ret++;
            }
        
        }
        return ret;
    }

}

看过排名靠前的后代码很简单,主要感觉是要对Java足够熟练,对对象的成员函数了解程度。就像string中的toCharArray()的使用。

class Solution {
    public int numJewelsInStones(String J, String S) {
        if(J.length()==0)
            return 0;
        int ret = 0;
        for(char c : S.toCharArray()){
        if(J.indexOf(c)!=-1) {
        ret ++;
        }
        }
        return ret;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值