(771)宝石与石头
Description:
给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
示例1:
Input: J = "aA", S = "aAAbbbb" Output: 3
示例2:
Input: J = "z", S = "ZZ" Output: 0
Note:
- S and J will consist of letters and have length at most 50.
- The characters in J are distinct
Code:
- my version:
from collections import Counter
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
c = Counter(S)
count = 0
for i in J:
count += c[i]
return count
- Other’s version:(only one line)
#摘自评论区
from collections import Counter
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
return sum(S.count(i) for i in J)
- C语言将所欲字母展开,搜索
//摘自评论区
int numJewelsInStones(char* J, char* S)
{
int w[58] = {0};
int count = 0;
char ch;
while(ch=*J++)
{
w[ch-'A']++;
}
while(ch=*S++)
{
if(w[ch-'A'])
count++;
}
return count;
}