Jewels and Stones

HeeSeong·2021년 8월 10일
0

LeetCode

목록 보기
2/38
post-thumbnail

🔗 문제 링크

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.



💡 풀이 (언어 : Java)


보석 문자열의 길이가 엄청 길어지면 시간 복잡도가 꽤 걸릴 듯 해서 보석 글자들을 먼저 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;   
    }
}
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글