You’re given strings
J
representing the types of stones that are jewels, andS
representing the stones you have. Each character inS
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
andS
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 inJ
are distinct.
나의 풀이
오랜만에 풀려니 머리가 잘 굴러가지 않는데 그럴땐 일단 가장 단순 무식한 방법으로 (Brute force 식으로) 풀어버리는 게 가장 좋은 것 같다.
1 | // 60ms |
아니 근데 반복문 2번은 돌려야 풀 수 있는 문제네;;1
2
3
4
5
6
7
8
9
10// 64ms
var numJewelsInStones = function(J, S) {
let num = 0;
for (const i of J) {
for (const j of S) {
j === i && num++
}
}
return num;
};
다른 사람 풀이
reduce 메서드를 이용한 방법1
2
3
4
5
6
7
8
9
10// 52ms
var numJewelsInStones = function(J, S) {
const jewels = J.split('');
return S.split('').reduce(function(a, b) {
if(jewels.includes(b)) {
a += 1;
}
return a;
}, 0)
}