leetcode - [771] Jewels and Stones

2020/06/28

问题描述

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

字符串J代表哪些类型的石头是宝石,字符串S代表你拥有的石头。

请计算你拥有的宝石数量。注意,字符串J中的字母都是唯一的,且大小写敏感。

举个例子:

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

Example 2:
Input: J = "z", S = "ZZ"
Output: 0

解法1

这道题挺简单,来梳理下思路:

首先,创建一个数组充当HashTable的作用。

然后,统计字符串S中每个字母出现的数量。

最后,遍历字符串J,统计所有宝石的数量。

来看下实现:

class Solution {
    public int numJewelsInStones(String J, String S) {
        
        int   ans = 0;
        int[] arr = new int[256];
        
        for (int i = 0; i < S.length(); i++){
            arr[S.charAt(i) - 'A']++;
        }
        
        for (int i = 0; i < J.length(); i++){
            ans += arr[J.charAt(i) - 'A'];
        }
        
        return ans;
    }
}

Thanks @hiepit

既然数组的长度设置成256,就没有必要再减去A了。

还有一点,可以在循环遍历时,可以将字符串转换成字符数组,使代码更为精简。

class Solution {
    public int numJewelsInStones(String J, String S) {
        
        int   ans = 0;
        int[] arr = new int[128];
        
        for (char c: S.toCharArray()){
            arr[c]++;
        }
        
        for (char c: J.toCharArray()){
            ans += arr[c];
        }
        
        return ans;
    }
}

Enjoy it !


一位喜欢提问、尝试的程序员

(转载本站文章请注明作者和出处 姚屹晨-yaoyichen

Post Directory