给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
输入: J = "aA", S = "aAAbbbb"
输出: 3
S
和J
最多含有50个字母。-
J
中的字符不重复。
方法1:暴力
class Solution {
public int numJewelsInStones(String J, String S) {
int ans = 0;
for (char s: S.toCharArray()) // For each stone...
for (char j: J.toCharArray()) // For each jewel...
if (j == s) { // If the stone is a jewel...
ans++;
break; // Stop searching whether this stone 's' is a jewel
}
return ans;
}
}
时间复杂度:O(J.length * S.length)
空间复杂度为 O(J.length * S.length) ==》 用charAt 降低为O(J.length + S.length)
方法2:哈希
class Solution {
public int numJewelsInStones(String J, String S) {
Set<Character> Jset = new HashSet();
for (char j: J.toCharArray())
Jset.add(j);
int ans = 0;
for (char s: S.toCharArray())
if (Jset.contains(s))
ans++;
return ans;
}
}
时间复杂度 O(J.length + S.length)
空间复杂度 O(J.length)