leetcode-771 Jewels and Stones

  1. 云栖社区>
  2. 博客>
  3. 正文

leetcode-771 Jewels and Stones

翁小炉 2018-02-28 16:46:47 浏览792

Q: 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

S: 常规解决方法:java

1.public int numJewelsInStones(String J, String S) {
        int res = 0;
        Set setJ = new HashSet();
        for (char j: J.toCharArray()) setJ.add(j);
        for (char s: S.toCharArray()) if (setJ.contains(s)) res++;
        return res;

public int numJewelsInStones(String J, String S) {
    return S.replaceAll("[^" + J + "]", "").length();


+ 关注