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".
理解一下:
J和S都是字符串(char数组).
S中包含多少个J所包含的单个字符(char)
需要区分大小写
例子:
Input: J = "aA", S = "aAAbbbb"
Output: 3
例子:
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.
翻译: J最大长度为50. J.length <= 50
我的答案
class Solution {
func numJewelsInStones(_ J: String, _ S: String) -> Int {
var count = 0
var j_dic = [Character: Int]()
for (offset , element) in J.enumerated() {
j_dic[element] = offset
}
for (_, element) in S.enumerated() {
if let _ = j_dic[element] {
count += 1
}
}
return count
}
}
如果有更好的解法, 欢迎留言
网友评论