issues
search
spring-comes-to-us
/
algorithm-comes-to-us
알고리즘 스터디!
0
stars
0
forks
source link
[LeetCode] 771. Jewels and Stones
#33
Open
shoeone96
opened
9 months ago
shoeone96
commented
9 months ago
문제 링크
yenzip
commented
9 months ago
771. Jewels and Stones
언어: JAVA
성능: Time: 1 ms, Memory: 41.9 MB
코드 풀이
```java class Solution { public int numJewelsInStones(String jewels, String stones) { Set
st = new HashSet<>(); int answer = 0; for(char j : jewels.toCharArray()) { st.add(j); } for(char s : stones.toCharArray()) { if(st.contains(s)) { answer++; } } return answer; } } ```
코멘트
책을 안 보고 풀어봤을 때, Map보단 Set이 더 적합하지 않나 하고 Set으로 풀어봤습니다...!
shoeone96
commented
9 months ago
771. Jewels and Stones
언어: JAVA
성능: Time: 1 ms, Memory: 41.72 MB
코드 풀이
```java class Solution { public int numJewelsInStones(String jewels, String stones) { Map
map = new HashMap<>(); int answer = 0; for(int i = 0; i < stones.length(); i++){ map.put(stones.charAt(i), map.getOrDefault(stones.charAt(i), 0) + 1); } for(int i = 0; i < jewels.length(); i++){ if(map.containsKey(jewels.charAt(i))){ answer += map.get(jewels.charAt(i)); } } return answer; } } ```
코멘트
toCharArray로 향상된 for문을 쓸 때보다 바로 charAt 쓰는 게 속도는 빠르네요
Sehee-Lee-01
commented
9 months ago
Comment
stones에서 먼저 개수를 구하고 jewels 탐색하면서 다 더해주었습니다!
Code
```java import java.util.HashMap; import java.util.Map; class Solution { public int numJewelsInStones(String jewels, String stones) { Map
map = new HashMap<>(); for (char c : stones.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } int sumJewels = 0; for (char c : jewels.toCharArray()) { sumJewels += map.getOrDefault(c, 0); } return sumJewels; } } ```
ASak1104
commented
9 months ago
771. Jewels and Stones
언어 :
Kotlin
코드 :
깃허브
성능 : Time: 154 ms (67.02%), Space: 34.2 MB (85.86%)
Kotlin 풀이
```kt class Solution { val isJewels: IntArray = IntArray(58) fun numJewelsInStones(jewels: String, stones: String): Int { var count = 0 for (jewel in jewels) { isJewels[jewel - 'A'] = 1 } for (stone in stones) { count += isJewels[stone - 'A'] } return count } } ```
코멘트
Set
을 사용하면 쉽게 풀 수 있는 문제인 것 같습니다
저는
char
값을 index로 변환하는 방식으로 풀어봤어요!
문제 링크