You're given stringsJrepresenting the types of stones that are jewels, andSrepresenting the stones you have. Each character inSis a type of stone you have. You want to know how many of the stones you have are also jewels.

The letters inJare guaranteed distinct, and all characters inJandSare 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:

  • SandJwill consist of letters and have length at most 50.
  • The characters inJare distinct.

这个题比较简单,目测面试肯定不会出,过一遍J记录有哪些jewels,再过一遍S看看有多少jewels

class Solution {
    public int numJewelsInStones(String J, String S) {
        if(J == null || J.length() == 0)
            return 0;

        if(S == null || S.length() == 0)
            return 0;

        int res = 0;
        HashSet<Character> set = new HashSet<Character>();
        for(int i = 0; i < J.length(); i++) {
            set.add(J.charAt(i));
        }

        for(int i = 0; i < S.length(); i++) {
            if(set.contains(S.charAt(i)))
                res++;
        }

        return res;
    }
}

如果想要稍微提高点速度的话,可以用一个array代替hash set

class Solution {
    public int numJewelsInStones(String J, String S) {
        if(J == null || J.length() == 0)
            return 0;

        if(S == null || S.length() == 0)
            return 0;

        int res = 0;
        boolean[] map = new boolean[128];

        for(int i = 0; i < J.length(); i++) {
            map[J.charAt(i)] = true;
        }

        for(int i = 0; i < S.length(); i++) {
            if(map[S.charAt(i)]) {
                res++;
            }
        }

        return res;
    }
}

results matching ""

    No results matching ""