File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed
main/java/by/andd3dfx/string
test/java/by/andd3dfx/string Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments