[LeetCode] Jewels and Stones

준규·2023년 1월 23일

1.문제


You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so "a" is considered a different type of stone from "A".


영어 알파벳 각각이 stone 의 종류를 나타내는 stones 문자열이 주어지고 jewels 문자열이 주어질 때 stone 중 jewles 인 stone의 개수를 리턴하는 문제이다.


Example 1

Input: jewels = "aA", stones = "aAAbbbb"
Output: 3

Example 2

Input: jewels = "z", stones = "ZZ"
Output: 0

Constraints:

  • 1 <= jewels.length, stones.length <= 50
  • jewels and stones consist of only English letters.
  • All the characters of jewels are unique.

2.풀이

  1. stones를 반복문을 돌면서 jewels 문자열에 현재 stone 이 포함되어 있는지 체크한다.

/**
 * @param {string} jewels
 * @param {string} stones
 * @return {number}
 */
const numJewelsInStones = function (jewels, stones) {
  let count = 0;
  // stones 에서 jewels에 포함되어 있는 stone이면 count 를 1 증가시킨다
  stones.split("").forEach((stone) => {
    if (jewels.includes(stone)) {
      count++;
    }
  });

  return count;
};

3.결과

profile
안녕하세요 :)

0개의 댓글