LeetCode771. Jewels and Stones
1. 문제(원본)
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 and J will consist of letters and have length at most 50.
- The characters in J are distinct.
2. 문제
S문자열에서 J문자열에 포함된 캐릭터의 수를 구하라
3. 나의 답
class Solution {
func numJewelsInStones(_ J: String, _ S: String) -> Int {
var count = 0
J.forEach { (j) in
S.forEach { (s) in
if j == s {
count += 1
}
}
}
return count
}
}
4. 다른 유저의 답
#1
func numJewelsInStones(_ J: String, _ S: String) -> Int {
var jewels = 0
for s in S where J.contains(s) {
jewels += 1
}
return jewels
}
5. 마무리
저번과 비슷한 문제라고 생각하여 이중 포문을 사용해서 풀었지만
다른 유저의 답변을 보고 where과 contains를 사용하는 편이 더 나았을 것 같은 생각이 들었다.