Skip to content

Commit bb7f9b2

Browse files
committed
Add solution of JewelsAndStones task
1 parent ad2abfc commit bb7f9b2

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package by.andd3dfx.string;
2+
3+
import java.util.Set;
4+
import java.util.stream.Collectors;
5+
6+
/**
7+
* <pre>
8+
* <a href="https://leetcode.com/problems/jewels-and-stones/description/">Task description</a>
9+
*
10+
* You're given strings jewels representing the types of stones that are jewels, and stones
11+
* representing the stones you have. Each character in stones is a type of stone you have.
12+
* You want to know how many of the stones you have are also jewels.
13+
* Letters are case sensitive, so "a" is considered a different type of stone from "A".
14+
*
15+
* Example 1:
16+
* Input: jewels = "aA", stones = "aAAbbbb"
17+
* Output: 3
18+
*
19+
* Example 2:
20+
* Input: jewels = "z", stones = "ZZ"
21+
* Output: 0
22+
* </pre>
23+
*/
24+
public class JewelsAndStones {
25+
26+
public static int numJewelsInStones(String jewels, String stones) {
27+
var count = 0;
28+
for (var ch : stones.toCharArray()) {
29+
if (jewels.indexOf(ch) != -1) {
30+
count++;
31+
}
32+
}
33+
return count;
34+
}
35+
36+
public static int numJewelsInStones2(String jewels, String stones) {
37+
Set<Character> jewelsSet = jewels.chars()
38+
.mapToObj(jewel -> (char) jewel)
39+
.collect(Collectors.toSet());
40+
41+
return (int) stones.chars()
42+
.mapToObj(stone -> (char) stone)
43+
.filter(jewelsSet::contains)
44+
.count();
45+
}
46+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package by.andd3dfx.string;
2+
3+
import static by.andd3dfx.string.JewelsAndStones.numJewelsInStones;
4+
import static by.andd3dfx.string.JewelsAndStones.numJewelsInStones2;
5+
import static org.assertj.core.api.Assertions.assertThat;
6+
7+
import org.junit.Test;
8+
9+
public class JewelsAndStonesTest {
10+
11+
@Test
12+
public void testNumJewelsInStones() {
13+
assertThat(numJewelsInStones("aA", "aAAbbbb")).isEqualTo(3);
14+
assertThat(numJewelsInStones("z", "ZZ")).isEqualTo(0);
15+
}
16+
17+
@Test
18+
public void testNumJewelsInStones2() {
19+
assertThat(numJewelsInStones2("aA", "aAAbbbb")).isEqualTo(3);
20+
assertThat(numJewelsInStones2("z", "ZZ")).isEqualTo(0);
21+
}
22+
}

0 commit comments

Comments
 (0)