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"
.
Note:
S
andJ
will consist of letters and have length at most 50.- The characters in
J
are distinct.
给定字符串 J 表示宝石类型,S表示你拥有的石头。S中的每个字符都是一种石头。你想知道你有多少石头是宝石。
J 中的字母保证是不同的,而J和S中的所有字符都是字母。字母是区分大小写的,所以“a”被认为是与“A”不同的一种石头。
注意:
S 和 J 由字母组成,长度最多为50。
J 中的字符是不同的。
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
方法一: 时间复杂度:O(n^2) 空间复杂度:O(1)
public int numJewelsInStones(String J, String S) {
int result = 0;
char[] j = J.toCharArray();
char[] s = S.toCharArray();
for(int na = 0 ; na < j.length ; na++) {
for(int nb = 0 ; nb < s.length ; nb++) {
if(j[na] == s[nb])
result ++;
}
}
return result;
}
方法二: 时间复杂度:O(n) 空间复杂度:O(n)
public int numJewelsInStones(String J, String S) {
Set<Character> jSet = new HashSet<>();
for(Character ch : J.toCharArray()) {
jSet.add(ch);
}
int result = 0;
for(Character ch: S.toCharArray()) {
if(jSet.contains(ch)) {
result ++;
}
}
return result;
}