Leetcode 771. Jewels and Stones
一个字符代表一种是宝石(Jewels),一串(Stones)字符串有多少个宝石。
Letters are case sensitive. 区分大小写。
For example:
“aA”
“abAaAAbbbb”
return 5
Approach #1: Brute Force [Accepted]
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;
}
}
Approach #2: Hash Set [Accepted]
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;
}
}