LeetCode 771. Jewels and Stones

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

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.

此题是找出J中的字符在S中的个数,本人的解法时间复杂度为O(n),空间复杂度为O(1),就是感觉代码稍嫌繁琐,Accepted代码如下:

class Solution {
    public int numJewelsInStones(String J, String S) {
        int lj = J.length();
        int ls = S.length();
        if (lj == 0 || ls == 0) {
            return 0;
        }
        int[] A = new int[26];
        int[] B = new int[26];
        for (int i = 0; i < lj; i++) {
            char c = J.charAt(i);
            if ( c >= 'a' && c <= 'z') {
                A[c - 'a']++;
            }
            if ( c >= 'A' && c <= 'Z') {
                B[c - 'A']++;
            }
        }
        int sum = 0;
        for (int i = 0; i < ls; i++) {
            char c = S.charAt(i);
            if ( c >= 'a' && c <= 'z') {
                if (A[c - 'a'] > 0) {
                    sum++;
                }
            }
            if ( c >= 'A' && c <= 'Z') {
                if (B[c - 'A'] > 0) {
                    sum++;
                }
            }
        }
        return sum;
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值