You're given stringsJ
representing the types of stones that are jewels, andS
representing the stones you have. Each character inS
is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters inJ
are guaranteed distinct, and all characters inJ
andS
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记录有哪些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;
}
}