771. Jewels and Stones
You’re given strings
The letters in
Example 1:
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
andJ
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; }