Jewels and Stones-LeetCode#771

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

思路:J为珠宝的石头类型,S为有的石头,求有多少数量的石头。J为字符截然不同的字符串。暴力搜索双重循环判断每个字符是否相同,时间复杂度为O(n²)。那么稍微优化后的解法,通过Set集合的contains方法,可以避免嵌套循环。
代码如下:

public static int numJewelsInStones(String J, String S) {
    int result = 0;
    Set setJ = new HashSet();
    for (char j : J.toCharArray()) {
        setJ.add(j);
    }
    for (char s : S.toCharArray()) {
        if (setJ.contains(s)) {
            result++;
        }
    }
    return result;
}
文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部