https://leetcode.com/problems/jewels-and-stones/
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".
1 <= jewels.length, stones.length <= 50
jewels and stones consist of only English letters.
All the characters of jewels are unique.
보석 문자열의 길이가 엄청 길어지면 시간 복잡도가 꽤 걸릴 듯 해서 보석 글자들을 먼저 HashSet에 넣어주어 각 돌의 글자마다 보석인지 조회하는 일을 O(1)로 줄였다.
import java.util.HashSet;
class Solution {
public int numJewelsInStones(String jewels, String stones) {
HashSet<Character> set = new HashSet<>();
int answer = 0;
for (char j : jewels.toCharArray())
set.add(j);
for (char s : stones.toCharArray()) {
if (set.contains(s))
answer++;
}
return answer;
}
}