LeetCode-771-Jewels and Stones(宝石和石头)

本文介绍了一个简单的编程问题,即计算给定字符串S中有多少字符出现在另一字符串J中,这里的J代表宝石,而S代表普通的石头。文章提供了一段Java代码示例来解决这个问题。

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

Q:

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".

 

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3

Example 2:

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.

 

Analysis:

此题的题意为给定字符串J为含有宝石的字符串,J中每个字符都可以成为一个宝石,S字符串是普通给定的石头,要查找出S中含有宝石的个数,即含有J中字符的个数,提示中说明J中字符均不相同,同时区分大小写。

解题思路:

直接遍历字符串S中的每个字符,同时判断如果该字符在J中出现,则S中含有宝石的数量+1,遍历完S后,即可得到结果,并将结果返回。

Code:

class Solution {
    public int numJewelsInStones(String J, String S) {
//      统计出现的次数
        int count=0;
//      将S遍历每个字符,查看String J中是否含有S的字符
        for(int i=0;i<S.length();i++){
            char c=S.charAt(i);
            String c1=String.valueOf(c);
            if(J.contains(c1)){
//              含有的话数量+1
                count++;
            }
        }
        return count;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值