Jewels and Stones

leetcode 문제링크

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.

나의 풀이

오랜만에 풀려니 머리가 잘 굴러가지 않는데 그럴땐 일단 가장 단순 무식한 방법으로 (Brute force 식으로) 풀어버리는 게 가장 좋은 것 같다.

1
2
3
4
5
6
7
8
9
10
11
12
// 60ms
var numJewelsInStones = function(J, S) {
let num = 0;
const jArr = J.split('');
const sArr = S.split('');
for (let i = 0, l = jArr.length; i < l; i++) {
for (let j = 0, m = sArr.length; j < m; j++) {
sArr[j] === jArr[i] && num++;
}
}
return num;
};

아니 근데 반복문 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)
}

Share Comments