https://leetcode.com/problems/jewels-and-stones/description/
https://leetcode.com/problems/jewels-and-stones/discuss/113553/C++JavaPython-Easy-and-Concise-Solution-O(M+N)
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
andJ
will consist of letters and have length at most 50.- The characters in
J
are distinct.
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;
}
https://leetcode.com/problems/jewels-and-stones/discuss/113574/1-liners-PythonJavaRubypublic int numJewelsInStones(String J, String S) {
return S.replaceAll("[^" + J + "]", "").length();
}
https://leetcode.com/problems/jewels-and-stones/discuss/113562/Java-solutionint res = 0, index = 0;
for (int i = 0; i < J.length(); i++) {
char jewel = J.charAt(i);
while ((index = S.indexOf(String.valueOf(jewel), index)) != -1) {
++res;
++index;
}
}
return res;
https://www.cnblogs.com/grandyang/p/8910994.html
这道题给了我们两个字符串,珠宝字符串J和石头字符串S,其中J中的每个字符都是珠宝,S中的每个字符都是石头,问我们S中有多少个珠宝。这道题没什么难度,高于八成的Accept率也应证了其Easy难度实至名归。那么先来暴力搜索吧,就将S中的每个字符都在J中搜索一遍,搜索到了就break掉,