題目:
給定字元串J 代表石頭中寶石的類型,和字元串 S代表你擁有的石頭。 S 中每個字元代表了一種你擁有的石頭的類型,你想知道你擁有的石頭中有多少是寶石。
J 中的字母不重複,J 和 S中的所有字元都是字母。字母區分大小寫,是以"a"和"A"是不同類型的石頭。
示例 1:
輸入: J = "aA", S = "aAAbbbb"
輸出: 3
示例 2:
輸入: J = "z", S = "ZZ"
輸出: 0
注意:
S 和 J 最多含有50個字母。
J 中的字元不重複。

Python(Java)執行個體學習教程:寶石與石頭
Note:
S and J will consist of letters and have length at most 50.
The characters in J are distinct.
解題思路:
J 改為 Set 集合, 周遊 S 即可(因為 Set 查找複雜度為常數)
Java:
class Solution {
public int numJewelsInStones(String J, String S) {
Set set = new HashSet<>();
for (char c : J.toCharArray())
set.add(c);
int count = 0;
for (char c : S.toCharArray())
if (set.contains(c)) count++;
return count;
}
}
Python:
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
count = 0
hash_set = set(J)
for c in S:
if c in hash_set:
count += 1
return count
更多的學習教程會繼續為大家更新!