[LeetCode] 771. Jewels and Stones 珠宝和石头
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"
.
Example 1:
Input: J = "aA", S = "aAAbbbb" Output: 3
Example 2:
Input: J = "z", S = "ZZ" Output: 0
Note:
S
andJ
will consist of letters and have length at most 50.- The characters in
J
are distinct.
给两个字符串,珠宝字符串J和石头字符串S,其中J中的每个字符都是珠宝,S中的每个字符都是石头,区分字母的大小写,问我们S中有多少个珠宝。
Java:
1 2 3 | public int numJewelsInStones(String J, String S) { return S.replaceAll( "[^" + J + "]" , "" ).length(); } |
Java:
1 2 3 4 5 6 7 | public int numJewelsInStones(String J, String S) { int res = 0 ; Set setJ = new HashSet(); for ( char j: J.toCharArray()) setJ.add(j); for ( char s: S.toCharArray()) if (setJ.contains(s)) res++; return res; } |
Python:
1 2 | def numJewelsInStones( self , J, S): return sum ( map (J.count, S)) |
Python:
1 2 | def numJewelsInStones( self , J, S): return sum ( map (S.count, J)) |
Python:
1 2 | def numJewelsInStones( self , J, S): return sum (s in J for s in S) |
Python:
1 2 3 | def numJewelsInStones( self , J, S): setJ = set (J) return sum (s in setJ for s in S) |
Python:
1 2 3 4 5 6 7 8 9 10 11 | # Time: O(m + n) # Space: O(n) class Solution( object ): def numJewelsInStones( self , J, S): """ :type J: str :type S: str :rtype: int """ lookup = set (J) return sum (s in lookup for s in S) |
Python: wo
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Solution( object ): def numJewelsInStones( self , J, S): """ :type J: str :type S: str :rtype: int """ res = 0 for i in S: if i in J: res + = 1 return res |
C++:
1 2 3 4 5 6 | int numJewelsInStones(string J, string S) { int res = 0; unordered_set< char > setJ(J.begin(), J.end()); for ( char s : S) if (setJ.count(s)) res++; return res; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步